From 263699ebe1423bdafb18dcef6239480c2a09b2e1 Mon Sep 17 00:00:00 2001 From: Anton Makeev Date: Wed, 1 Jul 2015 22:02:16 +0200 Subject: [PATCH 001/106] ProjectAndLibrariesScope now allows changing display name (in AppCode "Libraries" are "Frameworks") --- .../com/intellij/psi/search/ProjectAndLibrariesScope.java | 8 ++++++-- .../com/intellij/psi/search/ProjectScopeBuilderImpl.java | 7 +++++-- .../src/messages/PsiBundle.properties | 1 + 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/platform/indexing-api/src/com/intellij/psi/search/ProjectAndLibrariesScope.java b/platform/indexing-api/src/com/intellij/psi/search/ProjectAndLibrariesScope.java index 9217e15d7987..1f3cf14317bb 100644 --- a/platform/indexing-api/src/com/intellij/psi/search/ProjectAndLibrariesScope.java +++ b/platform/indexing-api/src/com/intellij/psi/search/ProjectAndLibrariesScope.java @@ -28,6 +28,7 @@ import java.util.List; public class ProjectAndLibrariesScope extends GlobalSearchScope { protected final ProjectFileIndex myProjectFileIndex; protected final boolean mySearchOutsideRootModel; + private String myDisplayName = PsiBundle.message("psi.search.scope.project.and.libraries"); public ProjectAndLibrariesScope(Project project) { this(project, false); @@ -88,7 +89,11 @@ public class ProjectAndLibrariesScope extends GlobalSearchScope { @NotNull public String getDisplayName() { - return PsiBundle.message("psi.search.scope.project.and.libraries"); + return myDisplayName; + } + + public void setDisplayName(@NotNull String displayName) { + myDisplayName = displayName; } @NotNull @@ -97,7 +102,6 @@ public class ProjectAndLibrariesScope extends GlobalSearchScope { return super.intersectWith(scope); } - return scope; } diff --git a/platform/indexing-impl/src/com/intellij/psi/search/ProjectScopeBuilderImpl.java b/platform/indexing-impl/src/com/intellij/psi/search/ProjectScopeBuilderImpl.java index 60fd53095dae..b586bf60901a 100644 --- a/platform/indexing-impl/src/com/intellij/psi/search/ProjectScopeBuilderImpl.java +++ b/platform/indexing-impl/src/com/intellij/psi/search/ProjectScopeBuilderImpl.java @@ -22,6 +22,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.FileIndexFacade; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.PsiBundle; import org.jetbrains.annotations.NotNull; /** @@ -38,7 +39,7 @@ public class ProjectScopeBuilderImpl extends ProjectScopeBuilder { @NotNull @Override public GlobalSearchScope buildLibrariesScope() { - return new ProjectAndLibrariesScope(myProject) { + ProjectAndLibrariesScope result = new ProjectAndLibrariesScope(myProject) { @Override public boolean contains(@NotNull VirtualFile file) { return myProjectFileIndex.isInLibrarySource(file) || myProjectFileIndex.isInLibraryClasses(file); @@ -49,6 +50,8 @@ public class ProjectScopeBuilderImpl extends ProjectScopeBuilder { return false; } }; + result.setDisplayName(PsiBundle.message("psi.search.scope.libraries")); + return result; } @NotNull @@ -65,7 +68,7 @@ public class ProjectScopeBuilderImpl extends ProjectScopeBuilder { return new ProjectAndLibrariesScope(myProject, searchOutsideRootModel); } - + @NotNull @Override public GlobalSearchScope buildProjectScope() { diff --git a/platform/platform-resources-en/src/messages/PsiBundle.properties b/platform/platform-resources-en/src/messages/PsiBundle.properties index 34a531c58def..0af4c52841ee 100644 --- a/platform/platform-resources-en/src/messages/PsiBundle.properties +++ b/platform/platform-resources-en/src/messages/PsiBundle.properties @@ -6,6 +6,7 @@ psi.search.for.word.progress=Searching for {0}... psi.search.in.non.java.files.progress=Analyzing non-code usages... psi.search.scope.project.and.libraries=Project and Libraries +psi.search.scope.libraries=Libraries psi.search.scope.project=Project Files psi.search.scope.production.files=Project Production Files psi.search.scope.test.files=Project Test Files From 09002b5a4171a90a3ef19bdbdeb3a0b5134d9758 Mon Sep 17 00:00:00 2001 From: Anton Makeev Date: Thu, 9 Jul 2015 13:24:50 +0200 Subject: [PATCH 002/106] FilenameIndex supports case-insensitive search --- .../com/intellij/index/FilenameIndexTest.java | 35 ++++++++++ .../intellij/psi/search/FilenameIndex.java | 66 +++++++++++++++---- 2 files changed, 90 insertions(+), 11 deletions(-) create mode 100644 java/java-tests/testSrc/com/intellij/index/FilenameIndexTest.java diff --git a/java/java-tests/testSrc/com/intellij/index/FilenameIndexTest.java b/java/java-tests/testSrc/com/intellij/index/FilenameIndexTest.java new file mode 100644 index 000000000000..d4962dfbefcb --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/index/FilenameIndexTest.java @@ -0,0 +1,35 @@ +/* + * Copyright 2000-2015 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.index; + +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.search.FilenameIndex; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase; + +public class FilenameIndexTest extends JavaCodeInsightFixtureTestCase { + public void testCaseInsensitiveFilesByName() throws Exception { + final VirtualFile vFile1 = myFixture.addFileToProject("dir1/foo.test", "Foo").getVirtualFile(); + final VirtualFile vFile2 = myFixture.addFileToProject("dir2/FOO.test", "Foo").getVirtualFile(); + + GlobalSearchScope scope = GlobalSearchScope.projectScope(getProject()); + assertSameElements(FilenameIndex.getVirtualFilesByName(getProject(), "foo.test", true, scope), vFile1); + assertSameElements(FilenameIndex.getVirtualFilesByName(getProject(), "FOO.test", true, scope), vFile2); + + assertSameElements(FilenameIndex.getVirtualFilesByName(getProject(), "foo.test", false, scope), vFile1, vFile2); + assertSameElements(FilenameIndex.getVirtualFilesByName(getProject(), "FOO.test", false, scope), vFile1, vFile2); + } +} diff --git a/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java b/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java index 134938d7815d..b826a8b79d45 100644 --- a/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java +++ b/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java @@ -18,7 +18,10 @@ package com.intellij.psi.search; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; +import com.intellij.psi.PsiDirectory; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiFileSystemItem; +import com.intellij.psi.PsiManager; import com.intellij.util.ArrayUtil; import com.intellij.util.CommonProcessors; import com.intellij.util.Processor; @@ -90,6 +93,14 @@ public class FilenameIndex extends ScalarIndexExtension { return FileBasedIndex.getInstance().getContainingFiles(NAME, name, scope); } + public static Collection getVirtualFilesByName(final Project project, + final String name, + boolean caseSensitively, + final GlobalSearchScope scope) { + if (caseSensitively) return getVirtualFilesByName(project, name, scope); + return getVirtualFilesByNameIgnoringCase(name, scope, null); + } + public static PsiFile[] getFilesByName(final Project project, final String name, final GlobalSearchScope scope) { return (PsiFile[])getFilesByName(project, name, scope, false); } @@ -99,17 +110,32 @@ public class FilenameIndex extends ScalarIndexExtension { @NotNull Processor processor, @NotNull GlobalSearchScope scope, @NotNull Project project, - @Nullable IdFilter idFilter - ) { - final Set files = new THashSet(); + @Nullable IdFilter idFilter) { + return processFilesByName(name, includeDirs, true, processor, scope, project, idFilter); + } + + public static boolean processFilesByName(@NotNull final String name, + boolean includeDirs, + boolean caseSensitively, + @NotNull Processor processor, + @NotNull final GlobalSearchScope scope, + @NotNull final Project project, + @Nullable IdFilter idFilter) { + final Set files; - FileBasedIndex.getInstance().processValues(NAME, name, null, new FileBasedIndex.ValueProcessor() { - @Override - public boolean process(final VirtualFile file, final Void value) { - files.add(file); - return true; - } - }, scope, idFilter); + if (caseSensitively) { + files = new THashSet(); + FileBasedIndex.getInstance().processValues(NAME, name, null, new FileBasedIndex.ValueProcessor() { + @Override + public boolean process(final VirtualFile file, final Void value) { + files.add(file); + return true; + } + }, scope, idFilter); + } + else { + files = getVirtualFilesByNameIgnoringCase(name, scope, idFilter); + } if (files.isEmpty()) return false; PsiManager psiManager = PsiManager.getInstance(project); @@ -134,6 +160,24 @@ public class FilenameIndex extends ScalarIndexExtension { return processedFiles > 0; } + @NotNull + private static Set getVirtualFilesByNameIgnoringCase(@NotNull final String name, + @NotNull final GlobalSearchScope scope, + @Nullable IdFilter idFilter) { + final Set files = new THashSet(); + final FileBasedIndex index = FileBasedIndex.getInstance(); + index.processAllKeys(NAME, new Processor() { + @Override + public boolean process(String value) { + if (name.equalsIgnoreCase(value)) { + files.addAll(index.getContainingFiles(NAME, value, scope)); + } + return true; + } + }, scope, idFilter); + return files; + } + public static PsiFileSystemItem[] getFilesByName(final Project project, final String name, @NotNull final GlobalSearchScope scope, From 03fc275c2b6232bc87edae29f50309eae4be3bfb Mon Sep 17 00:00:00 2001 From: Anton Makeev Date: Sat, 11 Jul 2015 17:15:36 +0200 Subject: [PATCH 003/106] FilenameIndex supports case-insensitive search (post review: more reliable keys-values processing) --- .../com/intellij/index/FilenameIndexTest.java | 6 +++--- .../src/com/intellij/psi/search/FilenameIndex.java | 12 +++++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/java/java-tests/testSrc/com/intellij/index/FilenameIndexTest.java b/java/java-tests/testSrc/com/intellij/index/FilenameIndexTest.java index d4962dfbefcb..dd0de6d318d4 100644 --- a/java/java-tests/testSrc/com/intellij/index/FilenameIndexTest.java +++ b/java/java-tests/testSrc/com/intellij/index/FilenameIndexTest.java @@ -23,13 +23,13 @@ import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase; public class FilenameIndexTest extends JavaCodeInsightFixtureTestCase { public void testCaseInsensitiveFilesByName() throws Exception { final VirtualFile vFile1 = myFixture.addFileToProject("dir1/foo.test", "Foo").getVirtualFile(); - final VirtualFile vFile2 = myFixture.addFileToProject("dir2/FOO.test", "Foo").getVirtualFile(); + final VirtualFile vFile2 = myFixture.addFileToProject("dir2/FOO.TEST", "Foo").getVirtualFile(); GlobalSearchScope scope = GlobalSearchScope.projectScope(getProject()); assertSameElements(FilenameIndex.getVirtualFilesByName(getProject(), "foo.test", true, scope), vFile1); - assertSameElements(FilenameIndex.getVirtualFilesByName(getProject(), "FOO.test", true, scope), vFile2); + assertSameElements(FilenameIndex.getVirtualFilesByName(getProject(), "FOO.TEST", true, scope), vFile2); assertSameElements(FilenameIndex.getVirtualFilesByName(getProject(), "foo.test", false, scope), vFile1, vFile2); - assertSameElements(FilenameIndex.getVirtualFilesByName(getProject(), "FOO.test", false, scope), vFile1, vFile2); + assertSameElements(FilenameIndex.getVirtualFilesByName(getProject(), "FOO.TEST", false, scope), vFile1, vFile2); } } diff --git a/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java b/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java index b826a8b79d45..88b11c19d0ef 100644 --- a/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java +++ b/platform/indexing-impl/src/com/intellij/psi/search/FilenameIndex.java @@ -163,18 +163,24 @@ public class FilenameIndex extends ScalarIndexExtension { @NotNull private static Set getVirtualFilesByNameIgnoringCase(@NotNull final String name, @NotNull final GlobalSearchScope scope, - @Nullable IdFilter idFilter) { - final Set files = new THashSet(); + @Nullable final IdFilter idFilter) { + final Set keys = new THashSet(); final FileBasedIndex index = FileBasedIndex.getInstance(); index.processAllKeys(NAME, new Processor() { @Override public boolean process(String value) { if (name.equalsIgnoreCase(value)) { - files.addAll(index.getContainingFiles(NAME, value, scope)); + keys.add(value); } return true; } }, scope, idFilter); + + // values accessed outside of provessAllKeys + final Set files = new THashSet(); + for (String each : keys) { + files.addAll(index.getContainingFiles(NAME, each, scope)); + } return files; } From 1756b27635d7f1c92cd474764d059dc3c5856a29 Mon Sep 17 00:00:00 2001 From: Anton Makeev Date: Thu, 16 Jul 2015 21:23:46 +0200 Subject: [PATCH 004/106] some UsefulTestCase made available statically --- .../com/intellij/testFramework/UsefulTestCase.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java b/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java index ccb652b87d28..52b238a47758 100644 --- a/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/UsefulTestCase.java @@ -542,21 +542,21 @@ public abstract class UsefulTestCase extends TestCase { } } - public void assertContainsOrdered(Collection collection, T... expected) { + public static void assertContainsOrdered(Collection collection, T... expected) { assertContainsOrdered(collection, Arrays.asList(expected)); } - public void assertContainsOrdered(Collection collection, Collection expected) { + public static void assertContainsOrdered(Collection collection, Collection expected) { ArrayList copy = new ArrayList(collection); copy.retainAll(expected); assertOrderedEquals(toString(collection), copy, expected); } - public void assertContainsElements(Collection collection, T... expected) { + public static void assertContainsElements(Collection collection, T... expected) { assertContainsElements(collection, Arrays.asList(expected)); } - public void assertContainsElements(Collection collection, Collection expected) { + public static void assertContainsElements(Collection collection, Collection expected) { ArrayList copy = new ArrayList(collection); copy.retainAll(expected); assertSameElements(toString(collection), copy, expected); @@ -566,11 +566,11 @@ public abstract class UsefulTestCase extends TestCase { return toString(Arrays.asList(collection), separator); } - public void assertDoesntContain(Collection collection, T... notExpected) { + public static void assertDoesntContain(Collection collection, T... notExpected) { assertDoesntContain(collection, Arrays.asList(notExpected)); } - public void assertDoesntContain(Collection collection, Collection notExpected) { + public static void assertDoesntContain(Collection collection, Collection notExpected) { ArrayList expected = new ArrayList(collection); expected.removeAll(notExpected); assertSameElements(collection, expected); From 67ae5c1e9594774367326a5c8d11e2a3abb8c5f5 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 10:14:39 +0200 Subject: [PATCH 005/106] failure in LocalHistoryActionsTest.tearDown shouldn't bring down other tests --- .../history/integration/ui/LocalHistoryActionsTest.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/platform/platform-tests/testSrc/com/intellij/history/integration/ui/LocalHistoryActionsTest.java b/platform/platform-tests/testSrc/com/intellij/history/integration/ui/LocalHistoryActionsTest.java index bbcbe9b4c2f2..33dbf02f8c84 100644 --- a/platform/platform-tests/testSrc/com/intellij/history/integration/ui/LocalHistoryActionsTest.java +++ b/platform/platform-tests/testSrc/com/intellij/history/integration/ui/LocalHistoryActionsTest.java @@ -49,8 +49,12 @@ public class LocalHistoryActionsTest extends LocalHistoryUITestCase { @Override protected void tearDown() throws Exception { - getEditorFactory().releaseEditor(editor); - super.tearDown(); + try { + getEditorFactory().releaseEditor(editor); + } + finally { + super.tearDown(); + } } private static EditorFactory getEditorFactory() { From 47ce99429f7021a759578961c1093dc03fc40e19 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 10:15:08 +0200 Subject: [PATCH 006/106] fix status bar progress leaks --- .../openapi/wm/impl/status/InfoAndProgressPanel.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java index d5a7e920ffc0..7603d4697942 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java @@ -242,7 +242,10 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge myPopup.removeIndicator(progress); final ProgressIndicatorEx original = removeFromMaps(progress); - if (myOriginals.contains(original)) return; + if (myOriginals.contains(original)) { + Disposer.dispose(progress); + return; + } if (last) { restoreEmptyStatus(); From a060898025463b086469483b6087da84d00e0d08 Mon Sep 17 00:00:00 2001 From: Aleksey Pivovarov Date: Mon, 20 Jul 2015 11:08:58 +0300 Subject: [PATCH 007/106] diff: codereview --- .../openapi/ui/WindowWrapperBuilder.java | 74 +++++++++---------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/WindowWrapperBuilder.java b/platform/platform-impl/src/com/intellij/openapi/ui/WindowWrapperBuilder.java index 1b144d71c0c0..742e99060957 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/WindowWrapperBuilder.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/WindowWrapperBuilder.java @@ -14,66 +14,66 @@ import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class WindowWrapperBuilder { - @NotNull private final Mode mode; - @NotNull private final JComponent component; - @Nullable private Project project; - @Nullable private Component parent; - @Nullable private String title; - @Nullable private JComponent preferredFocusedComponent; - @Nullable private String dimensionServiceKey; - @Nullable private Runnable onShowCallback; + @NotNull private final Mode myMode; + @NotNull private final JComponent myComponent; + @Nullable private Project myProject; + @Nullable private Component myParent; + @Nullable private String myTitle; + @Nullable private JComponent myPreferredFocusedComponent; + @Nullable private String myDimensionServiceKey; + @Nullable private Runnable myOnShowCallback; public WindowWrapperBuilder(@NotNull Mode mode, @NotNull JComponent component) { - this.mode = mode; - this.component = component; + myMode = mode; + myComponent = component; } @NotNull public WindowWrapperBuilder setProject(@Nullable Project project) { - this.project = project; + myProject = project; return this; } @NotNull public WindowWrapperBuilder setParent(@Nullable Component parent) { - this.parent = parent; + myParent = parent; return this; } @NotNull public WindowWrapperBuilder setTitle(@Nullable String title) { - this.title = title; + myTitle = title; return this; } @NotNull public WindowWrapperBuilder setPreferredFocusedComponent(@Nullable JComponent preferredFocusedComponent) { - this.preferredFocusedComponent = preferredFocusedComponent; + myPreferredFocusedComponent = preferredFocusedComponent; return this; } @NotNull public WindowWrapperBuilder setDimensionServiceKey(@Nullable String dimensionServiceKey) { - this.dimensionServiceKey = dimensionServiceKey; + myDimensionServiceKey = dimensionServiceKey; return this; } @NotNull public WindowWrapperBuilder setOnShowCallback(@NotNull Runnable callback) { - this.onShowCallback = callback; + myOnShowCallback = callback; return this; } @NotNull public WindowWrapper build() { - switch (mode) { + switch (myMode) { case FRAME: return new FrameWindowWrapper(this); case MODAL: case NON_MODAL: return new DialogWindowWrapper(this); default: - throw new IllegalArgumentException(mode.toString()); + throw new IllegalArgumentException(myMode.toString()); } } @@ -85,18 +85,18 @@ public class WindowWrapperBuilder { @NotNull private final DialogWrapper myDialog; public DialogWindowWrapper(@NotNull final WindowWrapperBuilder builder) { - myProject = builder.project; - myComponent = builder.component; - myMode = builder.mode; + myProject = builder.myProject; + myComponent = builder.myComponent; + myMode = builder.myMode; - if (builder.parent != null) { - myDialog = new MyDialogWrapper(builder.parent, builder.component, builder.dimensionServiceKey, builder.preferredFocusedComponent); + if (builder.myParent != null) { + myDialog = new MyDialogWrapper(builder.myParent, builder.myComponent, builder.myDimensionServiceKey, builder.myPreferredFocusedComponent); } else { - myDialog = new MyDialogWrapper(builder.project, builder.component, builder.dimensionServiceKey, builder.preferredFocusedComponent); + myDialog = new MyDialogWrapper(builder.myProject, builder.myComponent, builder.myDimensionServiceKey, builder.myPreferredFocusedComponent); } - final Runnable onShowCallback = builder.onShowCallback; + final Runnable onShowCallback = builder.myOnShowCallback; if (onShowCallback != null) { myDialog.getWindow().addWindowListener(new WindowAdapter() { @Override @@ -106,8 +106,8 @@ public class WindowWrapperBuilder { }); } - setTitle(builder.title); - switch (builder.mode) { + setTitle(builder.myTitle); + switch (builder.myMode) { case MODAL: myDialog.setModal(true); break; @@ -115,7 +115,7 @@ public class WindowWrapperBuilder { myDialog.setModal(false); break; default: - throw new IllegalArgumentException(builder.mode.toString()); + throw new IllegalArgumentException(builder.myMode.toString()); } myDialog.init(); Disposer.register(myDialog.getDisposable(), this); @@ -241,18 +241,18 @@ public class WindowWrapperBuilder { @NotNull private final FrameWrapper myFrame; public FrameWindowWrapper(@NotNull WindowWrapperBuilder builder) { - myProject = builder.project; - myComponent = builder.component; - myMode = builder.mode; - myOnShowCallback = builder.onShowCallback; + myProject = builder.myProject; + myComponent = builder.myComponent; + myMode = builder.myMode; + myOnShowCallback = builder.myOnShowCallback; - myFrame = new FrameWrapper(builder.project, builder.dimensionServiceKey); + myFrame = new FrameWrapper(builder.myProject, builder.myDimensionServiceKey); - assert builder.mode == Mode.FRAME; + assert builder.myMode == Mode.FRAME; - myFrame.setComponent(builder.component); - myFrame.setPreferredFocusedComponent(builder.preferredFocusedComponent); - myFrame.setTitle(builder.title); + myFrame.setComponent(builder.myComponent); + myFrame.setPreferredFocusedComponent(builder.myPreferredFocusedComponent); + myFrame.setTitle(builder.myTitle); myFrame.closeOnEsc(); Disposer.register(myFrame, this); } From e4e97724f16c7b38fe582bd735d9af3883b7e973 Mon Sep 17 00:00:00 2001 From: Dmitry Batrak Date: Mon, 20 Jul 2015 10:31:22 +0300 Subject: [PATCH 008/106] IDEA-126561 Quick documentation (ctrl+q) popup keyboard navigation --- .../documentation/DocumentationComponent.java | 139 ++++++++++++++++-- 1 file changed, 123 insertions(+), 16 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java index 50d8c8b71cae..d7d2e8e43ee3 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java @@ -32,6 +32,7 @@ import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.impl.ActionButton; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; @@ -66,7 +67,8 @@ import javax.swing.event.ChangeListener; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.*; -import javax.swing.text.html.HTMLEditorKit; +import javax.swing.text.html.HTML; +import javax.swing.text.html.HTMLDocument; import java.awt.*; import java.awt.event.*; import java.net.URL; @@ -74,7 +76,9 @@ import java.util.*; import java.util.List; public class DocumentationComponent extends JPanel implements Disposable, DataProvider { + private static Logger LOGGER = Logger.getInstance(DocumentationComponent.class); + private static final Highlighter.HighlightPainter LINK_HIGHLIGHTER = new LinkHighlighter(); @NonNls private static final String DOCUMENTATION_TOPIC_ID = "reference.toolWindows.Documentation"; private static final int PREFERRED_WIDTH_EM = 37; @@ -113,11 +117,13 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr private final SmartPsiElementPointer element; private final String text; private final Rectangle viewRect; + private final int highlightedLink; - public Context(SmartPsiElementPointer element, String text, Rectangle viewRect) { + public Context(SmartPsiElementPointer element, String text, Rectangle viewRect, int highlightedLink) { this.element = element; this.text = text; this.viewRect = viewRect; + this.highlightedLink = highlightedLink; } } @@ -128,6 +134,8 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr private boolean myControlPanelVisible; private final ExternalDocAction myExternalDocAction; private Consumer myNavigateCallback; + private int myHighlightedLink = -1; + private Object myHighlightingTag; private JBPopup myHint; @@ -150,11 +158,6 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr myIsShown = false; myEditorPane = new JEditorPane(UIUtil.HTML_MIME, "") { - @Override - public EditorKit getEditorKit() { - return new HTMLEditorKit(); - } - @Override public Dimension getPreferredScrollableViewportSize() { int em = myEditorPane.getFont().getSize(); @@ -342,6 +345,10 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr } } + new NextLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("TAB"), this); + new PreviousLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("shift TAB"), this); + new ActivateLinkAction().registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), this); + myToolBar = ActionManager.getInstance().createActionToolbar(ActionPlaces.JAVADOC_TOOLBAR, actions, true); myControlPanel = new JPanel(new BorderLayout(5, 5)); @@ -548,12 +555,10 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr if (clearHistory) clearHistory(); } - private void setDataInternal(SmartPsiElementPointer element, String text, final Rectangle viewRect, String ref) { - setDataInternal(element, text, viewRect, ref, false); - } - - private void setDataInternal(SmartPsiElementPointer element, String text, final Rectangle viewRect, final String ref, boolean skip) { + private void setDataInternal(SmartPsiElementPointer element, String text, final Rectangle viewRect, final String ref) { setElement(element); + + highlightLink(-1); myEditorPane.setText(text); applyFontSize(); @@ -563,9 +568,7 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr myIsShown = true; } - if (!skip) { - myText = text; - } + myText = text; //noinspection SSBasedInspection SwingUtilities.invokeLater(new Runnable() { @@ -620,7 +623,7 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr private Context saveContext() { Rectangle rect = myScrollPane.getViewport().getViewRect(); - return new Context(myElement, myText, rect); + return new Context(myElement, myText, rect, myHighlightedLink); } private void restoreContext(Context context) { @@ -631,6 +634,7 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr myNavigateCallback.consume(element); } } + highlightLink(context.highlightedLink); } private void updateControlState() { @@ -864,6 +868,61 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr myNavigateCallback = null; } + private int getLinkCount() { + HTMLDocument document = (HTMLDocument)myEditorPane.getDocument(); + int linkCount = 0; + for (HTMLDocument.Iterator it = document.getIterator(HTML.Tag.A); it.isValid(); it.next()) { + if (it.getAttributes().isDefined(HTML.Attribute.HREF)) linkCount++; + } + return linkCount; + } + + @Nullable + private HTMLDocument.Iterator getLink(int n) { + if (n >= 0) { + HTMLDocument document = (HTMLDocument)myEditorPane.getDocument(); + int linkCount = 0; + for (HTMLDocument.Iterator it = document.getIterator(HTML.Tag.A); it.isValid(); it.next()) { + if (it.getAttributes().isDefined(HTML.Attribute.HREF) && linkCount++ == n) return it; + } + } + return null; + } + + private void highlightLink(int n) { + myHighlightedLink = n; + Highlighter highlighter = myEditorPane.getHighlighter(); + HTMLDocument.Iterator link = getLink(n); + if (link != null) { + int startOffset = link.getStartOffset(); + int endOffset = link.getEndOffset(); + try { + if (myHighlightingTag == null) { + myHighlightingTag = highlighter.addHighlight(startOffset, endOffset, LINK_HIGHLIGHTER); + } + else { + highlighter.changeHighlight(myHighlightingTag, startOffset, endOffset); + } + myEditorPane.setCaretPosition(startOffset); + } + catch (BadLocationException e) { + LOGGER.warn("Error highlighting link", e); + } + } + else if (myHighlightingTag != null) { + highlighter.removeHighlight(myHighlightingTag); + myHighlightingTag = null; + } + } + + private void activateLink(int n) { + HTMLDocument.Iterator link = getLink(n); + if (link != null) { + String href = (String)link.getAttributes().getAttribute(HTML.Attribute.HREF); + myManager.navigateByLink(this, href); + } + } + private class MyShowSettingsButton extends ActionButton { private MyShowSettingsButton() { @@ -936,4 +995,52 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr throw new UnsupportedOperationException(); } } + + private class PreviousLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { + @Override + public void actionPerformed(AnActionEvent e) { + int linkCount = getLinkCount(); + if (linkCount <= 0) return; + highlightLink(myHighlightedLink < 0 ? (linkCount - 1) : (myHighlightedLink + linkCount - 1) % linkCount); + } + } + + private class NextLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { + @Override + public void actionPerformed(AnActionEvent e) { + int linkCount = getLinkCount(); + if (linkCount <= 0) return; + highlightLink((myHighlightedLink + 1) % linkCount); + } + } + + private class ActivateLinkAction extends AnAction implements HintManagerImpl.ActionToIgnore { + @Override + public void actionPerformed(AnActionEvent e) { + activateLink(myHighlightedLink); + } + } + + private static class LinkHighlighter implements Highlighter.HighlightPainter { + private static final Stroke STROKE = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, new float[]{1}, 0); + + @Override + public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { + try { + Rectangle target = c.getUI().getRootView(c).modelToView(p0, Position.Bias.Forward, p1, Position.Bias.Backward, bounds).getBounds(); + Graphics2D g2d = (Graphics2D)g.create(); + try { + g2d.setStroke(STROKE); + g2d.setColor(c.getSelectionColor()); + g2d.drawRect(target.x, target.y, target.width - 1, target.height - 1); + } + finally { + g2d.dispose(); + } + } + catch (Exception e) { + LOGGER.warn("Error painting link highlight", e); + } + } + } } From d3d52b447eb6808ab6c944feaf87da7e640cf0a9 Mon Sep 17 00:00:00 2001 From: Dmitry Batrak Date: Mon, 20 Jul 2015 11:28:17 +0300 Subject: [PATCH 009/106] enable back/forward navigation in quick doc component using mouse --- .../documentation/DocumentationComponent.java | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java index d7d2e8e43ee3..2ea545b7234c 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java @@ -37,9 +37,11 @@ import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; import com.intellij.openapi.editor.ex.util.EditorUtil; +import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.options.FontSize; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.ex.WindowManagerEx; @@ -331,8 +333,22 @@ public class DocumentationComponent extends JPanel implements Disposable, DataPr actions.add(myExternalDocAction = new ExternalDocAction()); actions.add(edit); - back.registerCustomShortcutSet(CustomShortcutSet.fromString("LEFT"), this); - forward.registerCustomShortcutSet(CustomShortcutSet.fromString("RIGHT"), this); + try { + CustomShortcutSet backShortcutSet = new CustomShortcutSet(KeyboardShortcut.fromString("LEFT"), + KeymapUtil.parseMouseShortcut("button4")); + CustomShortcutSet forwardShortcutSet = new CustomShortcutSet(KeyboardShortcut.fromString("RIGHT"), + KeymapUtil.parseMouseShortcut("button5")); + back.registerCustomShortcutSet(backShortcutSet, this); + forward.registerCustomShortcutSet(forwardShortcutSet, this); + // mouse actions are checked only for exact component over which click was performed, + // so we need to register shortcuts for myEditorPane as well + back.registerCustomShortcutSet(backShortcutSet, myEditorPane); + forward.registerCustomShortcutSet(forwardShortcutSet, myEditorPane); + } + catch (InvalidDataException e) { + LOGGER.error(e); + } + myExternalDocAction.registerCustomShortcutSet(CustomShortcutSet.fromString("UP"), this); edit.registerCustomShortcutSet(CommonShortcuts.getEditSource(), this); if (additionalActions != null) { From 036d617d2826b3a77ec2db63efa6c30597915b56 Mon Sep 17 00:00:00 2001 From: "Egor.Ushakov" Date: Mon, 20 Jul 2015 12:05:36 +0300 Subject: [PATCH 010/106] fixed blinking testApplet --- .../src/com/intellij/debugger/impl/OutputChecker.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/testFramework/src/com/intellij/debugger/impl/OutputChecker.java b/java/testFramework/src/com/intellij/debugger/impl/OutputChecker.java index d1de77dcd09e..a23d8b98823c 100644 --- a/java/testFramework/src/com/intellij/debugger/impl/OutputChecker.java +++ b/java/testFramework/src/com/intellij/debugger/impl/OutputChecker.java @@ -211,7 +211,7 @@ public class OutputChecker { result = result.replaceAll("!HOST_NAME!:\\d*", "!HOST_NAME!:!HOST_PORT!"); result = result.replaceAll("at \\'.*?\\'", "at '!HOST_NAME!:PORT_NAME!'"); result = result.replaceAll("address: \\'.*?\\'", "address: '!HOST_NAME!:PORT_NAME!'"); - result = result.replaceAll("file:.*AppletPage.*\\.html", "file:!APPLET_HTML!"); + result = result.replaceAll("\"?file:.*AppletPage.*\\.html\"?", "file:!APPLET_HTML!"); result = result.replaceAll("\"(!JDK_HOME!.*?)\"", "$1"); result = result.replaceAll("\"(!APP_PATH!.*?)\"", "$1"); result = result.replaceAll("\"(" + TEST_JDK_HOME_STR + ".*?)\"", "$1"); From 264c3b103f801f62c24b792f3b1909b6b87c7018 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 10:54:34 +0200 Subject: [PATCH 011/106] preventing excessive tests failures: create editors associated with a project --- .../com/intellij/projectView/FileStructureDialogTest.java | 2 +- .../history/integration/ui/LocalHistoryActionsTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/java/java-tests/testSrc/com/intellij/projectView/FileStructureDialogTest.java b/java/java-tests/testSrc/com/intellij/projectView/FileStructureDialogTest.java index d7b6fda9fad0..eda81a3be9a3 100644 --- a/java/java-tests/testSrc/com/intellij/projectView/FileStructureDialogTest.java +++ b/java/java-tests/testSrc/com/intellij/projectView/FileStructureDialogTest.java @@ -49,7 +49,7 @@ public class FileStructureDialogTest extends BaseProjectViewTestCase { final Document document = FileDocumentManager.getInstance().getDocument(virtualFile); assertNotNull(document); - final Editor editor = factory.createEditor(document); + final Editor editor = factory.createEditor(document, myProject); try { final FileStructureDialog dialog = new FileStructureDialog(structureViewModel, editor, myProject, psiClass, new Disposable() { diff --git a/platform/platform-tests/testSrc/com/intellij/history/integration/ui/LocalHistoryActionsTest.java b/platform/platform-tests/testSrc/com/intellij/history/integration/ui/LocalHistoryActionsTest.java index 33dbf02f8c84..edd5b35765cb 100644 --- a/platform/platform-tests/testSrc/com/intellij/history/integration/ui/LocalHistoryActionsTest.java +++ b/platform/platform-tests/testSrc/com/intellij/history/integration/ui/LocalHistoryActionsTest.java @@ -44,7 +44,7 @@ public class LocalHistoryActionsTest extends LocalHistoryUITestCase { document = FileDocumentManager.getInstance().getDocument(f); document.setText("foo"); - editor = getEditorFactory().createEditor(document); + editor = getEditorFactory().createEditor(document, myProject); } @Override From 437cdd7c4e11870ad2ce32395ccb11dde46cf9d6 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 10:54:53 +0200 Subject: [PATCH 012/106] fix NPE via GotoDeclarationAction.update --- .../codeInsight/actions/BaseCodeInsightAction.java | 3 +-- .../codeInsight/hint/actions/ShowContainerInfoAction.java | 2 +- .../navigation/actions/GotoDeclarationAction.java | 8 +++++++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/BaseCodeInsightAction.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/BaseCodeInsightAction.java index 4dc3c699027e..61cce0c6e293 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/actions/BaseCodeInsightAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/BaseCodeInsightAction.java @@ -21,7 +21,6 @@ import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; @@ -68,7 +67,7 @@ public abstract class BaseCodeInsightAction extends CodeInsightAction { } @Nullable - protected Editor getBaseEditor(final DataContext dataContext, final Project project) { + protected Editor getBaseEditor(@NotNull final DataContext dataContext, @NotNull final Project project) { return super.getEditor(dataContext, project); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hint/actions/ShowContainerInfoAction.java b/platform/lang-impl/src/com/intellij/codeInsight/hint/actions/ShowContainerInfoAction.java index 1cb27b29ad58..52c027975fed 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/actions/ShowContainerInfoAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/actions/ShowContainerInfoAction.java @@ -37,7 +37,7 @@ public class ShowContainerInfoAction extends BaseCodeInsightAction{ @Override @Nullable - protected Editor getBaseEditor(final DataContext dataContext, final Project project) { + protected Editor getBaseEditor(@NotNull final DataContext dataContext, @NotNull final Project project) { return CommonDataKeys.EDITOR_EVEN_IF_INACTIVE.getData(dataContext); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java index 1aa926aa31f9..dd42b6c06a69 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java @@ -271,7 +271,13 @@ public class GotoDeclarationAction extends BaseCodeInsightAction implements Code if (component != null) { Point point = ((MouseEvent)inputEvent).getPoint(); Component componentAt = SwingUtilities.getDeepestComponentAt(component, point.x, point.y); - Editor editor = getBaseEditor(event.getDataContext(), event.getProject()); + Project project = event.getProject(); + if (project == null) { + event.getPresentation().setEnabled(false); + return; + } + + Editor editor = getBaseEditor(event.getDataContext(), project); if (componentAt instanceof EditorGutterComponentEx) { event.getPresentation().setEnabled(false); return; From 1a5b0e06a0b3f21778b210dc42e7ced4ec8b8d1b Mon Sep 17 00:00:00 2001 From: "Maxim.Mossienko" Date: Mon, 20 Jul 2015 11:24:47 +0200 Subject: [PATCH 013/106] extract duplicated code that creates tree / setups common actions --- .../hierarchy/TypeHierarchyBrowserBase.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/platform/lang-impl/src/com/intellij/ide/hierarchy/TypeHierarchyBrowserBase.java b/platform/lang-impl/src/com/intellij/ide/hierarchy/TypeHierarchyBrowserBase.java index 0b2efcc29c42..2e5b7062a1e9 100644 --- a/platform/lang-impl/src/com/intellij/ide/hierarchy/TypeHierarchyBrowserBase.java +++ b/platform/lang-impl/src/com/intellij/ide/hierarchy/TypeHierarchyBrowserBase.java @@ -24,8 +24,12 @@ import com.intellij.ide.util.DeleteHandler; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; +import com.intellij.ui.PopupHandler; import org.jetbrains.annotations.NotNull; +import javax.swing.*; +import java.util.Map; + public abstract class TypeHierarchyBrowserBase extends HierarchyBrowserBaseEx { @SuppressWarnings({"UnresolvedPropertyKey"}) @@ -48,6 +52,27 @@ public abstract class TypeHierarchyBrowserBase extends HierarchyBrowserBaseEx { protected abstract boolean isInterface(PsiElement psiElement); + protected void createTreeAndSetupCommonActions(@NotNull Map trees, ActionGroup group) { + final BaseOnThisTypeAction baseOnThisTypeAction = new BaseOnThisTypeAction(); + final JTree tree1 = createTree(true); + PopupHandler.installPopupHandler(tree1, group, ActionPlaces.TYPE_HIERARCHY_VIEW_POPUP, ActionManager.getInstance()); + baseOnThisTypeAction + .registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_TYPE_HIERARCHY).getShortcutSet(), tree1); + trees.put(TYPE_HIERARCHY_TYPE, tree1); + + final JTree tree2 = createTree(true); + PopupHandler.installPopupHandler(tree2, group, ActionPlaces.TYPE_HIERARCHY_VIEW_POPUP, ActionManager.getInstance()); + baseOnThisTypeAction + .registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_TYPE_HIERARCHY).getShortcutSet(), tree2); + trees.put(SUPERTYPES_HIERARCHY_TYPE, tree2); + + final JTree tree3 = createTree(true); + PopupHandler.installPopupHandler(tree3, group, ActionPlaces.TYPE_HIERARCHY_VIEW_POPUP, ActionManager.getInstance()); + baseOnThisTypeAction + .registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_TYPE_HIERARCHY).getShortcutSet(), tree3); + trees.put(SUBTYPES_HIERARCHY_TYPE, tree3); + } + protected abstract boolean canBeDeleted(PsiElement psiElement); protected abstract String getQualifiedName(PsiElement psiElement); From 52a4a829ed9cb0b50fe3d31336b11977503de7a3 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Mon, 20 Jul 2015 12:25:37 +0300 Subject: [PATCH 014/106] IDEA-142751 Use replace rather than replaceAll to avoid pattern matcher and regex use --- .../com/intellij/openapi/options/newEditor/SettingsDialog.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsDialog.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsDialog.java index 71e9b3073cee..915cd2d85031 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsDialog.java @@ -72,7 +72,7 @@ public class SettingsDialog extends DialogWrapper implements DataProvider { String name = configurable == null ? null : configurable.getDisplayName(); String title = CommonBundle.settingsTitle(); if (project != null && project.isDefault()) title = "Default " + title; - setTitle(name == null ? title : name.replaceAll("\n", " ")); + setTitle(name == null ? title : name.replace('\n', ' ')); init(); } From c8614d69a2c6b6c66a9e9314b7555702cc3cc602 Mon Sep 17 00:00:00 2001 From: Sergey Savenko Date: Mon, 20 Jul 2015 12:17:55 +0300 Subject: [PATCH 015/106] ContainerUtil: add createConcurrentSoftMap method --- .../src/com/intellij/util/containers/ContainerUtil.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/platform/util/src/com/intellij/util/containers/ContainerUtil.java b/platform/util/src/com/intellij/util/containers/ContainerUtil.java index 7232d1627d22..e562bede0b92 100644 --- a/platform/util/src/com/intellij/util/containers/ContainerUtil.java +++ b/platform/util/src/com/intellij/util/containers/ContainerUtil.java @@ -2470,6 +2470,15 @@ public class ContainerUtil extends ContainerUtilRt { } @NotNull @Contract(pure=true) + public static ConcurrentMap createConcurrentSoftMap(int initialCapacity, + float loadFactor, + int concurrencyLevel, + @NotNull TObjectHashingStrategy hashingStrategy) { + //noinspection deprecation + return new ConcurrentSoftHashMap(initialCapacity, loadFactor, concurrencyLevel, hashingStrategy); + } + @NotNull + @Contract(pure=true) public static ConcurrentMap createConcurrentWeakMap(int initialCapacity, float loadFactor, int concurrencyLevel, From 571af7e4253a0fb00058fa28b43a5d129a0b66c9 Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 12:16:06 +0200 Subject: [PATCH 016/106] remove duplicate tip declaration --- resources/src/META-INF/IdeTipsAndTricks.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/resources/src/META-INF/IdeTipsAndTricks.xml b/resources/src/META-INF/IdeTipsAndTricks.xml index 5169a84ac519..c2d128152200 100644 --- a/resources/src/META-INF/IdeTipsAndTricks.xml +++ b/resources/src/META-INF/IdeTipsAndTricks.xml @@ -158,7 +158,6 @@ - From 32efbd6d187f6a1f9a4871537fc5506c8601adf0 Mon Sep 17 00:00:00 2001 From: Eugene Zhuravlev Date: Mon, 20 Jul 2015 12:13:37 +0200 Subject: [PATCH 017/106] IDEA-142104 Determine JDK version without waiting for external process on EDT --- .../java/impl/JdkVersionDetectorImpl.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/jps/model-impl/src/org/jetbrains/jps/model/java/impl/JdkVersionDetectorImpl.java b/jps/model-impl/src/org/jetbrains/jps/model/java/impl/JdkVersionDetectorImpl.java index 205bae0a1a8f..9e0edb9e4da8 100644 --- a/jps/model-impl/src/org/jetbrains/jps/model/java/impl/JdkVersionDetectorImpl.java +++ b/jps/model-impl/src/org/jetbrains/jps/model/java/impl/JdkVersionDetectorImpl.java @@ -25,6 +25,8 @@ import org.jetbrains.jps.service.SharedThreadPool; import java.io.*; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicReference; +import java.util.jar.JarFile; +import java.util.jar.Manifest; /** * @author nik @@ -46,6 +48,36 @@ public class JdkVersionDetectorImpl extends JdkVersionDetector { @Nullable public String detectJdkVersion(@NotNull String homePath, @NotNull final ActionRunner actionRunner) { + final File path = new File(homePath, "jre/lib/rt.jar"); + try { + JarFile runtimeArchive; + try { + runtimeArchive = new JarFile(path, false); + } + catch (IOException e) { + try { + runtimeArchive = new JarFile(path.getParentFile(), false); + } + catch (IOException e1) { + // jdk9 case. Alternatively, if jrt-fs.jar is not available, we could read the 'release' file + runtimeArchive = new JarFile(new File(homePath, "jrt-fs.jar")); + } + } + try { + final Manifest manifest = runtimeArchive.getManifest(); + if (manifest != null) { + final String version = manifest.getMainAttributes().getValue("Implementation-Version"); + if (version != null) { + return "java version \"" + version + "\""; + } + } + } + finally { + runtimeArchive.close(); + } + } + catch (IOException ignored) { + } JdkVersionInfo info = detectJdkVersionInfo(homePath, actionRunner); if (info != null) { return info.getVersion(); From e0d4d154d6890b8d73af5ebe84b30bc26af34c4e Mon Sep 17 00:00:00 2001 From: Dmitry Avdeev Date: Fri, 17 Jul 2015 20:03:08 +0300 Subject: [PATCH 018/106] EA-70848 - NPE: DefaultXmlExtension.hasTag --- .../src/com/intellij/xml/DefaultXmlExtension.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/xml/xml-psi-impl/src/com/intellij/xml/DefaultXmlExtension.java b/xml/xml-psi-impl/src/com/intellij/xml/DefaultXmlExtension.java index de06f8cef03b..961c91497282 100644 --- a/xml/xml-psi-impl/src/com/intellij/xml/DefaultXmlExtension.java +++ b/xml/xml-psi-impl/src/com/intellij/xml/DefaultXmlExtension.java @@ -36,7 +36,7 @@ import java.util.*; * @author Dmitry Avdeev */ public class DefaultXmlExtension extends XmlExtension { - + @Override public boolean isAvailable(final PsiFile file) { return true; @@ -98,6 +98,10 @@ public class DefaultXmlExtension extends XmlExtension { private static boolean hasTag(@NotNull XmlElementDescriptor elementDescriptor, String tagName, Set visited) { final String name = elementDescriptor.getDefaultName(); + if (name == null) { + LOG.error(elementDescriptor + " returned null as default name"); + return false; + } if (name.equals(tagName)) { return true; } From 959ceaac165139d03f89e76087ed72e30540249f Mon Sep 17 00:00:00 2001 From: Dmitry Avdeev Date: Mon, 20 Jul 2015 13:53:17 +0300 Subject: [PATCH 019/106] EA-70328 - NPE: XMLExternalAnnotator.apply --- .../com/intellij/codeInsight/daemon/impl/ExternalToolPass.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ExternalToolPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ExternalToolPass.java index 52416d3743e1..dc8bda912c02 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ExternalToolPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ExternalToolPass.java @@ -157,7 +157,7 @@ public class ExternalToolPass extends ProgressableTextEditorHighlightingPass { private void applyRelevant() { for (ExternalAnnotator annotator : myAnnotator2DataMap.keySet()) { final MyData data = myAnnotator2DataMap.get(annotator); - if (data != null) { + if (data != null && data.myAnnotationResult != null) { annotator.apply(data.myPsiRoot, data.myAnnotationResult, myAnnotationHolder); } } From cc8601cf0ecf91efe0543b2d7cee7df2c7e667ee Mon Sep 17 00:00:00 2001 From: Dmitry Batrak Date: Mon, 20 Jul 2015 14:02:16 +0300 Subject: [PATCH 020/106] EA-69435 - NFE: RegistryValue.asInteger --- .../openapi/editor/impl/EditorImpl.java | 2 +- .../openapi/util/registry/Registry.java | 3 ++ .../openapi/util/registry/RegistryValue.java | 4 +-- .../openapi/util/registry/RegistryTest.java | 29 +++++++++++++++++++ 4 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 platform/util/testSrc/com/intellij/openapi/util/registry/RegistryTest.java diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java index 30fd0297d9d8..7dbad595a8f9 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java @@ -6114,7 +6114,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi if (myMousePressedEvent != null && myMousePressedEvent.getComponent() == e.getComponent()) { Point lastPoint = myMousePressedEvent.getPoint(); Point point = e.getPoint(); - int deadZone = Registry.intValue("editor.mouseSelectionStateResetDeadZone"); + int deadZone = Registry.intValue("editor.mouseSelectionStateResetDeadZone", 4); if (Math.abs(lastPoint.x - point.x) >= deadZone || Math.abs(lastPoint.y - point.y) >= deadZone) { resetMouseSelectionState(e); } diff --git a/platform/util/src/com/intellij/openapi/util/registry/Registry.java b/platform/util/src/com/intellij/openapi/util/registry/Registry.java index 32e2e4fe7f13..26599c0b968c 100644 --- a/platform/util/src/com/intellij/openapi/util/registry/Registry.java +++ b/platform/util/src/com/intellij/openapi/util/registry/Registry.java @@ -72,6 +72,9 @@ public class Registry { try { return get(key).asInteger(); } + catch (NumberFormatException ex) { + return defaultValue; + } catch (MissingResourceException ex) { return defaultValue; } diff --git a/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java b/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java index 96ddb5330f1f..a0ba6c5733e3 100644 --- a/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java +++ b/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java @@ -68,7 +68,7 @@ public class RegistryValue { return myBooleanCachedValue.booleanValue(); } - public int asInteger() { + public int asInteger() throws NumberFormatException { if (myIntCachedValue == null) { myIntCachedValue = Integer.valueOf(get(myKey, "0", true)); } @@ -76,7 +76,7 @@ public class RegistryValue { return myIntCachedValue.intValue(); } - public double asDouble() { + public double asDouble() throws NumberFormatException { if (myDoubleCachedValue == null) { myDoubleCachedValue = Double.valueOf(get(myKey, "0.0", true)); } diff --git a/platform/util/testSrc/com/intellij/openapi/util/registry/RegistryTest.java b/platform/util/testSrc/com/intellij/openapi/util/registry/RegistryTest.java new file mode 100644 index 000000000000..4fa667fe52d7 --- /dev/null +++ b/platform/util/testSrc/com/intellij/openapi/util/registry/RegistryTest.java @@ -0,0 +1,29 @@ +/* + * Copyright 2000-2015 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.util.registry; + +import org.junit.Test; + +import static junit.framework.Assert.assertEquals; + +@SuppressWarnings("UnresolvedPropertyKey") +public class RegistryTest { + @Test + public void testInvalidInteger() { + Registry.get("blah").setValue("invalidNumber"); + assertEquals(123, Registry.intValue("blah", 123)); + } +} \ No newline at end of file From a281d24943d6e9ee31d022cdd690a359d88f2672 Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 13:08:29 +0200 Subject: [PATCH 021/106] add fabric method for JBEmptyBorder(int) --- .../util/src/com/intellij/util/ui/JBUI.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/platform/util/src/com/intellij/util/ui/JBUI.java b/platform/util/src/com/intellij/util/ui/JBUI.java index 8cfc038aba9f..219eef130e39 100644 --- a/platform/util/src/com/intellij/util/ui/JBUI.java +++ b/platform/util/src/com/intellij/util/ui/JBUI.java @@ -59,7 +59,7 @@ public class JBUI { } public static int scale(int i) { - return isHiDPI() ? 2 * i : i; + return isHiDPI() ? (int)(1.5f * i) : i; } public static JBDimension size(int width, int height) { @@ -154,27 +154,31 @@ public class JBUI { } public static JBEmptyBorder empty(int topAndBottom, int leftAndRight) { - return new JBEmptyBorder(topAndBottom, leftAndRight, topAndBottom, leftAndRight); + return empty(topAndBottom, leftAndRight, topAndBottom, leftAndRight); } public static JBEmptyBorder emptyTop(int offset) { - return new JBEmptyBorder(offset, 0, 0, 0); + return empty(offset, 0, 0, 0); } public static JBEmptyBorder emptyLeft(int offset) { - return new JBEmptyBorder(0, offset, 0, 0); + return empty(0, offset, 0, 0); } public static JBEmptyBorder emptyBottom(int offset) { - return new JBEmptyBorder(0, 0, offset, 0); + return empty(0, 0, offset, 0); } public static JBEmptyBorder emptyRight(int offset) { - return new JBEmptyBorder(0, 0, 0, offset); + return empty(0, 0, 0, offset); } public static JBEmptyBorder empty() { - return new JBEmptyBorder(0); + return empty(0, 0, 0, 0); + } + + public static Border empty(int offsets) { + return empty(offsets, offsets, offsets, offsets); } public static Border customLine(Color color, int top, int left, int bottom, int right) { From 0004afe8bb166f8b7b191e62e6d8d8ab3811a090 Mon Sep 17 00:00:00 2001 From: Aleksey Pivovarov Date: Mon, 20 Jul 2015 13:32:03 +0300 Subject: [PATCH 022/106] ui: speedup UiUtil.drawAppleDottedLine() use a single big pattern (like in WavePainter) --- .../util/ui/AppleBoldDottedPainter.java | 105 ++++++++++++++++++ .../util/src/com/intellij/util/ui/UIUtil.java | 81 +------------- 2 files changed, 107 insertions(+), 79 deletions(-) create mode 100644 platform/util/src/com/intellij/util/ui/AppleBoldDottedPainter.java diff --git a/platform/util/src/com/intellij/util/ui/AppleBoldDottedPainter.java b/platform/util/src/com/intellij/util/ui/AppleBoldDottedPainter.java new file mode 100644 index 000000000000..bd4af246c908 --- /dev/null +++ b/platform/util/src/com/intellij/util/ui/AppleBoldDottedPainter.java @@ -0,0 +1,105 @@ +/* + * Copyright 2000-2015 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.util.ui; + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.util.HashMap; +import java.util.Map; + +/** + * Draws a 'apple-like' bold dotted line. Instances are cached for performance reasons. + *

+ * Each dot has this transparency core: + * | 20% | 50% | 20% | 0% | + * | 70% | 70% | 70% | 0% | + * | 50% | 100% | 50% | 0% | + *

+ * This class is not thread-safe, it's supposed to be used in EDT only. + */ +public class AppleBoldDottedPainter { + private static final int HEIGHT = 3; + private static final int WIDTH = 4; + + private static final Map myPainters = new HashMap(); + private static final int PATTERN_WIDTH = 4000; + + private final BufferedImage myImage; + + @SuppressWarnings("PointlessArithmeticExpression") + private AppleBoldDottedPainter(Color color) { + myImage = UIUtil.createImage(PATTERN_WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = myImage.createGraphics(); + try { + g.setColor(color); + for (int i = 0; i < PATTERN_WIDTH / WIDTH + 1; i++) { + int offset = i * WIDTH; + + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .2f)); + g.drawLine(offset + 0, 0, offset + 0, 0); + g.drawLine(offset + 2, 0, offset + 2, 0); + + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.7f)); + g.drawLine(offset + 0, 1, offset + 2, 1); + + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f)); + g.drawLine(offset + 1, 2, offset + 1, 2); + + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f)); + g.drawLine(offset + 1, 0, offset + 1, 0); + g.drawLine(offset + 0, 2, offset + 0, 2); + g.drawLine(offset + 2, 2, offset + 2, 2); + } + } + finally { + g.dispose(); + } + } + + public void paint(Graphics2D g, int xStart, int xEnd, int y) { + Shape oldClip = g.getClip(); + + final int startPosCorrection = xStart % WIDTH == WIDTH - 1 ? 1 : 0; + final int dotX0 = (xStart / WIDTH + startPosCorrection) * WIDTH; // draw lines in common phase + final int width = ((xEnd - dotX0 - 1) / WIDTH + 1) * WIDTH; // always paint whole dot + + final Rectangle rectangle = new Rectangle(dotX0, y, width, HEIGHT); + final Rectangle lineClip = oldClip != null ? oldClip.getBounds().intersection(rectangle) : rectangle; + if (lineClip.isEmpty()) return; + + Composite oldComposite = g.getComposite(); + try { + g.setComposite(AlphaComposite.SrcOver); + g.setClip(lineClip); + UIUtil.drawImage(g, myImage, dotX0, y, null); + } + finally { + g.setComposite(oldComposite); + g.setClip(oldClip); + } + } + + public static AppleBoldDottedPainter forColor(Color color) { + AppleBoldDottedPainter painter = myPainters.get(color); + if (painter == null) { + painter = new AppleBoldDottedPainter(color); + // creating a new Color instance, as the one passed as parameter can be mutable (JBColor) and shouldn't be used as a map key + //noinspection UseJBColor + myPainters.put(new Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()), painter); + } + return painter; + } +} diff --git a/platform/util/src/com/intellij/util/ui/UIUtil.java b/platform/util/src/com/intellij/util/ui/UIUtil.java index 6d1925926bfc..5f409b8540bb 100644 --- a/platform/util/src/com/intellij/util/ui/UIUtil.java +++ b/platform/util/src/com/intellij/util/ui/UIUtil.java @@ -267,9 +267,6 @@ public class UIUtil { } }; - // accessed only from EDT - private static final HashMap ourAppleDotSamples = new HashMap(); - private static volatile Pair ourSystemFontData = null; @NonNls private static final String ROOT_PANE = "JRootPane.future"; @@ -1677,82 +1674,8 @@ public class UIUtil { drawLine(g, startX, lineY + 2, endX, lineY + 2); } - // Draw apple like dotted line: - // - // CCC CCC CCC ... - // CCC CCC CCC ... - // CCC CCC CCC ... - // - // (where "C" - colored pixel, " " - white pixel) - - final int step = 4; - final int startPosCorrection = startX % step < 3 ? 0 : 1; - - // Optimization - lets draw dotted line using dot sample image. - - // draw one dot by pixel: - - // save old settings - final Composite oldComposite = g.getComposite(); - // draw image "over" on top of background - g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); - - // sample - final BufferedImage image = getAppleDotStamp(fgColor, oldColor); - - // Now copy our dot several times - final int dotX0 = (startX / step + startPosCorrection) * step; - for (int dotXi = dotX0; dotXi < endX; dotXi += step) { - g.drawImage(image, dotXi, lineY, null); - } - - //restore previous settings - g.setComposite(oldComposite); - } - - private static BufferedImage getAppleDotStamp(final Color fgColor, - final Color oldColor) { - final Color color = fgColor != null ? fgColor : oldColor; - - // let's avoid of generating tons of GC and store samples for different colors - BufferedImage sample = ourAppleDotSamples.get(color); - if (sample == null) { - sample = createAppleDotStamp(color); - ourAppleDotSamples.put(color, sample); - } - return sample; - } - - private static BufferedImage createAppleDotStamp(final Color color) { - final BufferedImage image = createImage(3, 3, BufferedImage.TYPE_INT_ARGB); - final Graphics2D g = image.createGraphics(); - - g.setColor(color); - - // Each dot: - // | 20% | 50% | 20% | - // | 80% | 80% | 80% | - // | 50% | 100% | 50% | - - g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .2f)); - g.drawLine(0, 0, 0, 0); - g.drawLine(2, 0, 2, 0); - - g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.7f)); - g.drawLine(0, 1, 2, 1); - - g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f)); - g.drawLine(1, 2, 1, 2); - - g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f)); - g.drawLine(1, 0, 1, 0); - g.drawLine(0, 2, 0, 2); - g.drawLine(2, 2, 2, 2); - - // dispose graphics - g.dispose(); - - return image; + AppleBoldDottedPainter painter = AppleBoldDottedPainter.forColor(ObjectUtils.notNull(fgColor, oldColor)); + painter.paint(g, startX, endX, lineY); } /** This method is intended to use when user settings are not accessible yet. From d5b361c760792b5f1e7bccfa95823b0000a16699 Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 13:13:35 +0200 Subject: [PATCH 023/106] simplify. Use same fabric method for borders with less parameters --- .../src/com/intellij/find/EditorSearchComponent.java | 8 ++++---- .../lang-impl/src/com/intellij/find/SearchWrapper.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/find/EditorSearchComponent.java b/platform/lang-impl/src/com/intellij/find/EditorSearchComponent.java index 588c322f56ac..ab6cb75b06de 100644 --- a/platform/lang-impl/src/com/intellij/find/EditorSearchComponent.java +++ b/platform/lang-impl/src/com/intellij/find/EditorSearchComponent.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -220,12 +220,12 @@ public class EditorSearchComponent extends EditorHeaderComponent implements Data Wrapper searchToolbarWrapper1 = new NonOpaquePanel(new BorderLayout()); searchToolbarWrapper1.add(mySearchActionsToolbar1, BorderLayout.WEST); Wrapper searchToolbarWrapper2 = new Wrapper(mySearchActionsToolbar2); - mySearchActionsToolbar2.setBorder(JBUI.Borders.empty(0, 16, 0, 0)); + mySearchActionsToolbar2.setBorder(JBUI.Borders.emptyLeft(16)); JPanel searchPair = new NonOpaquePanel(new BorderLayout()).setVerticalSizeReferent(mySearchFieldWrapper); searchPair.add(searchToolbarWrapper1, BorderLayout.WEST); searchPair.add(searchToolbarWrapper2, BorderLayout.CENTER); JLabel closeLabel = new JLabel(null, AllIcons.Actions.Cross, SwingConstants.RIGHT); - closeLabel.setBorder(JBUI.Borders.empty(5, 5, 5, 5)); + closeLabel.setBorder(JBUI.Borders.empty(5)); closeLabel.setVerticalAlignment(SwingConstants.TOP); closeLabel.addMouseListener(new MouseAdapter() { @Override @@ -239,7 +239,7 @@ public class EditorSearchComponent extends EditorHeaderComponent implements Data Wrapper replaceToolbarWrapper1 = new Wrapper(myReplaceActionsToolbar1).setVerticalSizeReferent(myReplaceFieldWrapper); Wrapper replaceToolbarWrapper2 = new Wrapper(myReplaceActionsToolbar2).setVerticalSizeReferent(myReplaceFieldWrapper); - myReplaceActionsToolbar2.setBorder(JBUI.Borders.empty(0, 16, 0, 0)); + myReplaceActionsToolbar2.setBorder(JBUI.Borders.emptyLeft(16)); myReplaceToolbarWrapper = new NonOpaquePanel(new BorderLayout()); myReplaceToolbarWrapper.add(replaceToolbarWrapper1, BorderLayout.WEST); diff --git a/platform/lang-impl/src/com/intellij/find/SearchWrapper.java b/platform/lang-impl/src/com/intellij/find/SearchWrapper.java index 650f02e9579c..3f37c3d0d9f7 100644 --- a/platform/lang-impl/src/com/intellij/find/SearchWrapper.java +++ b/platform/lang-impl/src/com/intellij/find/SearchWrapper.java @@ -51,7 +51,7 @@ class SearchWrapper extends NonOpaquePanel implements PropertyChangeListener, Fo scrollPane.getVerticalScrollBar().setBackground(UIUtil.TRANSPARENT_COLOR); scrollPane.getViewport().setBorder(null); scrollPane.getViewport().setOpaque(false); - scrollPane.setBorder(JBUI.Borders.empty(0, 0, 0, 2)); + scrollPane.setBorder(JBUI.Borders.emptyRight(2)); scrollPane.setOpaque(false); ActionButton button = new ActionButton(showHistoryAction, showHistoryAction.getTemplatePresentation(), ActionPlaces.UNKNOWN, new Dimension(JBUI.scale(16), JBUI.scale(16))); From dcb08abf0df67f4befbd30711fcdc5d956aca62d Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 13:14:01 +0200 Subject: [PATCH 024/106] simplify. Use same fabric method for borders with less parameters --- .../com/intellij/openapi/actionSystem/ex/ComboBoxAction.java | 4 ++-- .../com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java | 4 ++-- .../intellij/openapi/wm/impl/status/InfoAndProgressPanel.java | 2 +- .../src/com/intellij/openapi/wm/impl/status/StatusPanel.java | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java index 947bd507fa38..ed6e02e6eaab 100644 --- a/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java +++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -144,7 +144,7 @@ public abstract class ComboBoxAction extends AnAction implements CustomComponent Insets margins = getMargin(); setMargin(JBUI.insets(margins.top, 2, margins.bottom, 2)); if (isSmallVariant()) { - setBorder(JBUI.Borders.empty(0, 2, 0, 2)); + setBorder(JBUI.Borders.empty(0, 2)); if (!UIUtil.isUnderGTKLookAndFeel()) { setFont(JBUI.Fonts.label(11)); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java index c15f9afa14ce..0b0c8112bad6 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java @@ -448,8 +448,8 @@ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { final boolean nextIcon = n instanceof IconPresentationWrapper || n instanceof IconLikeCustomStatusBarWidget; // 2peter: please do not touch it anymore :) - self.setBorder(prevIcon ? JBUI.Borders.empty(2, 2, 2, 2) : StatusBarWidget.WidgetBorder.INSTANCE); - if (nextIcon) n.setBorder(JBUI.Borders.empty(2, 2, 2, 2)); + self.setBorder(prevIcon ? JBUI.Borders.empty(2) : StatusBarWidget.WidgetBorder.INSTANCE); + if (nextIcon) n.setBorder(JBUI.Borders.empty(2)); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java index 7603d4697942..877c85b0bd01 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java @@ -346,7 +346,7 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge add(myRefreshAndInfoPanel, BorderLayout.CENTER); - progressCountPanel.setBorder(JBUI.Borders.empty(0, 0, 0, 4)); + progressCountPanel.setBorder(JBUI.Borders.emptyRight(4)); add(progressCountPanel, BorderLayout.EAST); revalidate(); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/StatusPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/StatusPanel.java index 1faf5eb5b398..18870e5af785 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/StatusPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/StatusPanel.java @@ -97,7 +97,7 @@ class StatusPanel extends JPanel { setOpaque(false); - myTextPanel.setBorder(JBUI.Borders.empty(0, 5, 0, 0)); + myTextPanel.setBorder(JBUI.Borders.emptyLeft(5)); new ClickListener() { @Override public boolean onClick(@NotNull MouseEvent e, int clickCount) { From 2c536a1679ea83eef6d0ed1fd36af68e7068ef27 Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 13:23:33 +0200 Subject: [PATCH 025/106] rollback 1.5f scale factor. --- platform/util/src/com/intellij/util/ui/JBUI.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/util/src/com/intellij/util/ui/JBUI.java b/platform/util/src/com/intellij/util/ui/JBUI.java index 219eef130e39..c0aea56e2448 100644 --- a/platform/util/src/com/intellij/util/ui/JBUI.java +++ b/platform/util/src/com/intellij/util/ui/JBUI.java @@ -59,7 +59,7 @@ public class JBUI { } public static int scale(int i) { - return isHiDPI() ? (int)(1.5f * i) : i; + return isHiDPI() ? 2 * i : i; } public static JBDimension size(int width, int height) { From f8f24e714c8a0a6a1b805b991a7ce2df3be9939e Mon Sep 17 00:00:00 2001 From: Sergey Simonchik Date: Mon, 20 Jul 2015 14:48:16 +0300 Subject: [PATCH 026/106] semver: get rid of pattern matching --- .../src/com/intellij/util/text/SemVer.java | 44 +++++++++---------- .../com/intellij/util/text/SemVerTest.java | 28 +++++++++--- 2 files changed, 42 insertions(+), 30 deletions(-) diff --git a/platform/util/src/com/intellij/util/text/SemVer.java b/platform/util/src/com/intellij/util/text/SemVer.java index 5a37e1e8caf4..86de4010dfc1 100644 --- a/platform/util/src/com/intellij/util/text/SemVer.java +++ b/platform/util/src/com/intellij/util/text/SemVer.java @@ -15,19 +15,18 @@ */ package com.intellij.util.text; +import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.regex.Pattern; - /** - * See http://semver.org + * Holds Semantic Version. */ public class SemVer implements Comparable { + private final String myRawVersion; private final int myMajor; private final int myMinor; private final int myPatch; - private final String myRawVersion; public SemVer(@NotNull String rawVersion, int major, int minor, int patch) { myRawVersion = rawVersion; @@ -87,34 +86,31 @@ public class SemVer implements Comparable { @Nullable public static SemVer parseFromText(@NotNull String text) { - String[] comps = text.split(Pattern.quote("."), 3); - if (comps.length != 3) { + int majorEndInd = text.indexOf('.'); + if (majorEndInd < 0) { return null; } - Integer major = toInteger(comps[0]); - Integer minor = toInteger(comps[1]); - String patchStr = comps[2]; - int dashInd = patchStr.indexOf('-'); - if (dashInd >= 0) { - patchStr = patchStr.substring(0, dashInd); + int major = StringUtil.parseInt(text.substring(0, majorEndInd), -1); + int minorEndInd = text.indexOf('.', majorEndInd + 1); + if (minorEndInd < 0) { + return null; } - Integer patch = toInteger(patchStr); - if (major != null && minor != null && patch != null) { + int minor = StringUtil.parseInt(text.substring(majorEndInd + 1, minorEndInd), -1); + final String patchStr; + int dashInd = text.indexOf('-', minorEndInd + 1); + if (dashInd >= 0) { + patchStr = text.substring(minorEndInd + 1, dashInd); + } + else { + patchStr = text.substring(minorEndInd + 1); + } + int patch = StringUtil.parseInt(patchStr, -1); + if (major >= 0 && minor >= 0 && patch >= 0) { return new SemVer(text, major, minor, patch); } return null; } - private static Integer toInteger(@NotNull String str) { - try { - return Integer.parseInt(str); - } - catch (NumberFormatException e) { - return null; - } - } - - @Override public int compareTo(SemVer other) { // null is not permitted diff --git a/platform/util/testSrc/com/intellij/util/text/SemVerTest.java b/platform/util/testSrc/com/intellij/util/text/SemVerTest.java index 9d1328d9aca1..00f39f14aa73 100644 --- a/platform/util/testSrc/com/intellij/util/text/SemVerTest.java +++ b/platform/util/testSrc/com/intellij/util/text/SemVerTest.java @@ -20,18 +20,34 @@ import org.jetbrains.annotations.NotNull; public class SemVerTest extends TestCase { public void testParsing() throws Exception { - String version = "0.9.2"; - assertEquals(new SemVer(version, 0, 9, 2), parseNotNull(version)); + checkParsed("0.9.2", 0, 9, 2); } public void testExtendedVersion() throws Exception { - String version = "0.9.2-dart"; - assertEquals(new SemVer(version, 0, 9, 2), parseNotNull(version)); + checkParsed("0.9.2-dart", 0, 9, 2); } public void testGulp4Alpha() throws Exception { - String version = "4.0.0-alpha.1"; - assertEquals(new SemVer(version, 4, 0, 0), parseNotNull(version)); + checkParsed("4.0.0-alpha.1", 4, 0, 0); + } + + public void testMisc() throws Exception { + checkParsed("0.10.0-rc-1", 0, 10, 0); + checkParsed("1.0.0-rc-1", 1, 0, 0); + checkParsed("1.0.0-alpha", 1, 0, 0); + checkParsed("1.0.0-0.3.7", 1, 0, 0); + checkParsed("1.0.0-x.7.z.92", 1, 0, 0); + checkNotParsed("1.0.a"); + checkNotParsed("1.0"); + checkNotParsed("1..a"); + } + + private static void checkParsed(@NotNull String version, int expectedMajor, int expectedMinor, int expectedPatch) { + assertEquals(new SemVer(version, expectedMajor, expectedMinor, expectedPatch), parseNotNull(version)); + } + + private static void checkNotParsed(@NotNull String version) { + assertNull(SemVer.parseFromText(version)); } public void testCompare() throws Exception { From 3154459c2b50eff94b9bddbd7b4abaff771e52f9 Mon Sep 17 00:00:00 2001 From: Dmitry Semeniouta Date: Mon, 20 Jul 2015 14:47:56 +0300 Subject: [PATCH 027/106] AC/C++: fixes for installer TC configurations --- .../src/com/intellij/util/ui/tree/WideSelectionTreeUI.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/platform/util/src/com/intellij/util/ui/tree/WideSelectionTreeUI.java b/platform/util/src/com/intellij/util/ui/tree/WideSelectionTreeUI.java index 9824ccc7f28a..48a5eac7014e 100644 --- a/platform/util/src/com/intellij/util/ui/tree/WideSelectionTreeUI.java +++ b/platform/util/src/com/intellij/util/ui/tree/WideSelectionTreeUI.java @@ -132,7 +132,9 @@ public class WideSelectionTreeUI extends BasicTreeUI { @Override public void installUI(JComponent c) { super.installUI(c); - tree.setDragEnabled(true); + if (!GraphicsEnvironment.isHeadless()) { + tree.setDragEnabled(true); + } } @Override From 749f730f97ad42e2947899c1eaf6af3391c7ca9f Mon Sep 17 00:00:00 2001 From: Nikolay Mikhaylov Date: Mon, 20 Jul 2015 14:46:47 +0300 Subject: [PATCH 028/106] Load versions using Maven API --- .../maven/server/MavenServerEmbedder.java | 4 + .../maven2-server-impl/maven2-server-impl.iml | 4 +- .../embedder/Maven2ServerEmbedderImpl.java | 342 +++++++++------- .../maven/server/Maven3ServerEmbedder.java | 38 +- .../server/Maven30ServerEmbedderImpl.java | 384 ++++++++++-------- .../maven32-server-impl.iml | 45 +- .../server/Maven32ServerEmbedderImpl.java | 384 ++++++++++-------- .../maven/server/MavenEmbedderWrapper.java | 13 + .../library/RepositoryAttachHandler.java | 25 ++ 9 files changed, 719 insertions(+), 520 deletions(-) diff --git a/plugins/maven/maven-server-api/src/org/jetbrains/idea/maven/server/MavenServerEmbedder.java b/plugins/maven/maven-server-api/src/org/jetbrains/idea/maven/server/MavenServerEmbedder.java index 1082f3f60c18..5075db012054 100644 --- a/plugins/maven/maven-server-api/src/org/jetbrains/idea/maven/server/MavenServerEmbedder.java +++ b/plugins/maven/maven-server-api/src/org/jetbrains/idea/maven/server/MavenServerEmbedder.java @@ -35,6 +35,10 @@ public interface MavenServerEmbedder extends Remote { @NotNull MavenServerProgressIndicator indicator, boolean alwaysUpdateSnapshots) throws RemoteException; + @NotNull + List retrieveAvailableVersions(@NotNull String groupId, @NotNull String artifactId, @NotNull String remoteRepository) + throws RemoteException; + @NotNull MavenServerExecutionResult resolveProject(@NotNull File file, @NotNull Collection activeProfiles, diff --git a/plugins/maven/maven2-server-impl/maven2-server-impl.iml b/plugins/maven/maven2-server-impl/maven2-server-impl.iml index a2279495fd4c..8535710c36ad 100644 --- a/plugins/maven/maven2-server-impl/maven2-server-impl.iml +++ b/plugins/maven/maven2-server-impl/maven2-server-impl.iml @@ -93,6 +93,6 @@ + - - + \ No newline at end of file diff --git a/plugins/maven/maven2-server-impl/src/org/jetbrains/idea/maven/server/embedder/Maven2ServerEmbedderImpl.java b/plugins/maven/maven2-server-impl/src/org/jetbrains/idea/maven/server/embedder/Maven2ServerEmbedderImpl.java index 153cbf3f414e..a3843e05fcfb 100644 --- a/plugins/maven/maven2-server-impl/src/org/jetbrains/idea/maven/server/embedder/Maven2ServerEmbedderImpl.java +++ b/plugins/maven/maven2-server-impl/src/org/jetbrains/idea/maven/server/embedder/Maven2ServerEmbedderImpl.java @@ -22,16 +22,23 @@ import com.intellij.util.Function; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.artifact.manager.WagonManager; +import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; +import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; +import org.apache.maven.artifact.repository.DefaultArtifactRepository; +import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.artifact.repository.metadata.RepositoryMetadataManager; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.artifact.resolver.ResolutionListener; +import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.model.Activation; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; @@ -81,6 +88,11 @@ public class Maven2ServerEmbedderImpl extends MavenRemoteObject implements Maven private final Maven2ServerConsoleWrapper myConsoleWrapper; private volatile MavenServerProgressIndicator myCurrentIndicator; + private Maven2ServerEmbedderImpl(MavenEmbedder impl, Maven2ServerConsoleWrapper consoleWrapper) { + myImpl = impl; + myConsoleWrapper = consoleWrapper; + } + public static Maven2ServerEmbedderImpl create(MavenServerSettings facadeSettings) throws RemoteException { MavenEmbedderSettings settings = new MavenEmbedderSettings(); @@ -132,9 +144,147 @@ public class Maven2ServerEmbedderImpl extends MavenRemoteObject implements Maven return MavenEmbedderSettings.UpdatePolicy.DO_NOT_UPDATE; } - private Maven2ServerEmbedderImpl(MavenEmbedder impl, Maven2ServerConsoleWrapper consoleWrapper) { - myImpl = impl; - myConsoleWrapper = consoleWrapper; + private static Collection collectProfilesIds(List profiles) { + Collection result = new THashSet(); + for (Profile each : profiles) { + if (each.getId() != null) { + result.add(each.getId()); + } + } + return result; + } + + public static MavenModel interpolateAndAlignModel(MavenModel model, File basedir) throws RemoteException { + Model result = Maven2ModelConverter.toNativeModel(model); + result = doInterpolate(result, basedir); + + PathTranslator pathTranslator = new DefaultPathTranslator(); + pathTranslator.alignToBaseDirectory(result, basedir); + + return Maven2ModelConverter.convertModel(result, null); + } + + private static Model doInterpolate(Model result, File basedir) throws RemoteException { + try { + AbstractStringBasedModelInterpolator interpolator = new CustomModelInterpolator(new DefaultPathTranslator()); + interpolator.initialize(); + + Properties props = MavenServerUtil.collectSystemProperties(); + ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(props); + result = interpolator.interpolate(result, basedir, config, false); + } + catch (ModelInterpolationException e) { + Maven2ServerGlobals.getLogger().warn(e); + } + catch (InitializationException e) { + Maven2ServerGlobals.getLogger().error(e); + } + return result; + } + + public static MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) throws RemoteException { + Model result = Maven2ModelConverter.toNativeModel(model); + new DefaultModelInheritanceAssembler().assembleModelInheritance(result, Maven2ModelConverter.toNativeModel(parentModel)); + return Maven2ModelConverter.convertModel(result, null); + } + + public static ProfileApplicationResult applyProfiles(MavenModel model, + File basedir, + MavenExplicitProfiles explicitProfiles, + Collection alwaysOnProfiles) throws RemoteException { + Model nativeModel = Maven2ModelConverter.toNativeModel(model); + + Collection enabledProfiles = explicitProfiles.getEnabledProfiles(); + Collection disabledProfiles = explicitProfiles.getDisabledProfiles(); + List activatedPom = new ArrayList(); + List activatedExternal = new ArrayList(); + List activeByDefault = new ArrayList(); + + List rawProfiles = nativeModel.getProfiles(); + List expandedProfilesCache = null; + List deactivatedProfiles = new ArrayList(); + + for (int i = 0; i < rawProfiles.size(); i++) { + Profile eachRawProfile = rawProfiles.get(i); + + if (disabledProfiles.contains(eachRawProfile.getId())) { + deactivatedProfiles.add(eachRawProfile); + continue; + } + + boolean shouldAdd = enabledProfiles.contains(eachRawProfile.getId()) || alwaysOnProfiles.contains(eachRawProfile.getId()); + + Activation activation = eachRawProfile.getActivation(); + if (activation != null) { + if (activation.isActiveByDefault()) { + activeByDefault.add(eachRawProfile); + } + + // expand only if necessary + if (expandedProfilesCache == null) expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles(); + Profile eachExpandedProfile = expandedProfilesCache.get(i); + + for (ProfileActivator eachActivator : getProfileActivators(basedir)) { + try { + if (eachActivator.canDetermineActivation(eachExpandedProfile) && eachActivator.isActive(eachExpandedProfile)) { + shouldAdd = true; + break; + } + } + catch (ProfileActivationException e) { + Maven2ServerGlobals.getLogger().warn(e); + } + } + } + + if (shouldAdd) { + if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) { + activatedPom.add(eachRawProfile); + } + else { + activatedExternal.add(eachRawProfile); + } + } + } + + List activatedProfiles = new ArrayList(activatedPom.isEmpty() ? activeByDefault : activatedPom); + activatedProfiles.addAll(activatedExternal); + + for (Profile each : activatedProfiles) { + new DefaultProfileInjector().inject(each, nativeModel); + } + + return new ProfileApplicationResult(Maven2ModelConverter.convertModel(nativeModel, null), + new MavenExplicitProfiles(collectProfilesIds(activatedProfiles), + collectProfilesIds(deactivatedProfiles)) + ); + } + + private static ProfileActivator[] getProfileActivators(File basedir) throws RemoteException { + SystemPropertyProfileActivator sysPropertyActivator = new SystemPropertyProfileActivator(); + DefaultContext context = new DefaultContext(); + context.put("SystemProperties", MavenServerUtil.collectSystemProperties()); + try { + sysPropertyActivator.contextualize(context); + } + catch (ContextException e) { + Maven2ServerGlobals.getLogger().error(e); + return new ProfileActivator[0]; + } + + return new ProfileActivator[]{new MyFileProfileActivator(basedir), + sysPropertyActivator, + new JdkPrefixProfileActivator(), + new OperatingSystemProfileActivator()}; + } + + private static void setupContainer(PlexusContainer c) { + MavenEmbedder.setImplementation(c, ArtifactFactory.class, CustomArtifactFactory.class); + MavenEmbedder.setImplementation(c, ProjectArtifactFactory.class, CustomArtifactFactory.class); + MavenEmbedder.setImplementation(c, ArtifactResolver.class, CustomArtifactResolver.class); + MavenEmbedder.setImplementation(c, RepositoryMetadataManager.class, CustomRepositoryMetadataManager.class); + MavenEmbedder.setImplementation(c, WagonManager.class, CustomWagonManager.class); + MavenEmbedder.setImplementation(c, ModelInterpolator.class, CustomModelInterpolator.class); } @NotNull @@ -202,16 +352,6 @@ public class Maven2ServerEmbedderImpl extends MavenRemoteObject implements Maven return collectProfilesIds(profiles); } - private static Collection collectProfilesIds(List profiles) { - Collection result = new THashSet(); - for (Profile each : profiles) { - if (each.getId() != null) { - result.add(each.getId()); - } - } - return result; - } - @Nullable public String evaluateEffectivePom(@NotNull File file, @NotNull List activeProfiles, @NotNull List inactiveProfiles) { throw new UnsupportedOperationException(); @@ -400,130 +540,6 @@ public class Maven2ServerEmbedderImpl extends MavenRemoteObject implements Maven return result; } - public static MavenModel interpolateAndAlignModel(MavenModel model, File basedir) throws RemoteException { - Model result = Maven2ModelConverter.toNativeModel(model); - result = doInterpolate(result, basedir); - - PathTranslator pathTranslator = new DefaultPathTranslator(); - pathTranslator.alignToBaseDirectory(result, basedir); - - return Maven2ModelConverter.convertModel(result, null); - } - - private static Model doInterpolate(Model result, File basedir) throws RemoteException { - try { - AbstractStringBasedModelInterpolator interpolator = new CustomModelInterpolator(new DefaultPathTranslator()); - interpolator.initialize(); - - Properties props = MavenServerUtil.collectSystemProperties(); - ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(props); - result = interpolator.interpolate(result, basedir, config, false); - } - catch (ModelInterpolationException e) { - Maven2ServerGlobals.getLogger().warn(e); - } - catch (InitializationException e) { - Maven2ServerGlobals.getLogger().error(e); - } - return result; - } - - public static MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) throws RemoteException { - Model result = Maven2ModelConverter.toNativeModel(model); - new DefaultModelInheritanceAssembler().assembleModelInheritance(result, Maven2ModelConverter.toNativeModel(parentModel)); - return Maven2ModelConverter.convertModel(result, null); - } - - public static ProfileApplicationResult applyProfiles(MavenModel model, - File basedir, - MavenExplicitProfiles explicitProfiles, - Collection alwaysOnProfiles) throws RemoteException { - Model nativeModel = Maven2ModelConverter.toNativeModel(model); - - Collection enabledProfiles = explicitProfiles.getEnabledProfiles(); - Collection disabledProfiles = explicitProfiles.getDisabledProfiles(); - List activatedPom = new ArrayList(); - List activatedExternal = new ArrayList(); - List activeByDefault = new ArrayList(); - - List rawProfiles = nativeModel.getProfiles(); - List expandedProfilesCache = null; - List deactivatedProfiles = new ArrayList(); - - for (int i = 0; i < rawProfiles.size(); i++) { - Profile eachRawProfile = rawProfiles.get(i); - - if (disabledProfiles.contains(eachRawProfile.getId())) { - deactivatedProfiles.add(eachRawProfile); - continue; - } - - boolean shouldAdd = enabledProfiles.contains(eachRawProfile.getId()) || alwaysOnProfiles.contains(eachRawProfile.getId()); - - Activation activation = eachRawProfile.getActivation(); - if (activation != null) { - if (activation.isActiveByDefault()) { - activeByDefault.add(eachRawProfile); - } - - // expand only if necessary - if (expandedProfilesCache == null) expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles(); - Profile eachExpandedProfile = expandedProfilesCache.get(i); - - for (ProfileActivator eachActivator : getProfileActivators(basedir)) { - try { - if (eachActivator.canDetermineActivation(eachExpandedProfile) && eachActivator.isActive(eachExpandedProfile)) { - shouldAdd = true; - break; - } - } - catch (ProfileActivationException e) { - Maven2ServerGlobals.getLogger().warn(e); - } - } - } - - if (shouldAdd) { - if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) { - activatedPom.add(eachRawProfile); - } - else { - activatedExternal.add(eachRawProfile); - } - } - } - - List activatedProfiles = new ArrayList(activatedPom.isEmpty() ? activeByDefault : activatedPom); - activatedProfiles.addAll(activatedExternal); - - for (Profile each : activatedProfiles) { - new DefaultProfileInjector().inject(each, nativeModel); - } - - return new ProfileApplicationResult(Maven2ModelConverter.convertModel(nativeModel, null), - new MavenExplicitProfiles(collectProfilesIds(activatedProfiles), - collectProfilesIds(deactivatedProfiles)) - ); - } - - private static ProfileActivator[] getProfileActivators(File basedir) throws RemoteException { - SystemPropertyProfileActivator sysPropertyActivator = new SystemPropertyProfileActivator(); - DefaultContext context = new DefaultContext(); - context.put("SystemProperties", MavenServerUtil.collectSystemProperties()); - try { - sysPropertyActivator.contextualize(context); - } - catch (ContextException e) { - Maven2ServerGlobals.getLogger().error(e); - return new ProfileActivator[0]; - } - - return new ProfileActivator[]{new MyFileProfileActivator(basedir), - sysPropertyActivator, - new JdkPrefixProfileActivator(), - new OperatingSystemProfileActivator()}; - } - @NotNull public File getLocalRepositoryFile() { return myImpl.getLocalRepositoryFile(); @@ -541,10 +557,6 @@ public class Maven2ServerEmbedderImpl extends MavenRemoteObject implements Maven return myImpl.getContainer(); } - private interface Executor { - T execute() throws Exception; - } - private T doExecute(final Executor executor) throws MavenServerProcessCanceledException, RemoteException { final Ref result = new Ref(); final boolean[] cancelled = new boolean[1]; @@ -598,15 +610,6 @@ public class Maven2ServerEmbedderImpl extends MavenRemoteObject implements Maven return rethrowException(throwable); } - private static void setupContainer(PlexusContainer c) { - MavenEmbedder.setImplementation(c, ArtifactFactory.class, CustomArtifactFactory.class); - MavenEmbedder.setImplementation(c, ProjectArtifactFactory.class, CustomArtifactFactory.class); - MavenEmbedder.setImplementation(c, ArtifactResolver.class, CustomArtifactResolver.class); - MavenEmbedder.setImplementation(c, RepositoryMetadataManager.class, CustomRepositoryMetadataManager.class); - MavenEmbedder.setImplementation(c, WagonManager.class, CustomWagonManager.class); - MavenEmbedder.setImplementation(c, ModelInterpolator.class, CustomModelInterpolator.class); - } - public void customize(@Nullable MavenWorkspaceMap workspaceMap, boolean failOnUnresolvedDependency, @NotNull MavenServerConsole console, @@ -626,6 +629,41 @@ public class Maven2ServerEmbedderImpl extends MavenRemoteObject implements Maven } } + @NotNull + @Override + public List retrieveAvailableVersions(@NotNull String groupId, @NotNull String artifactId, @NotNull String remoteRepositoryUrl) + throws RemoteException { + try { + Artifact artifact = + new DefaultArtifact(groupId, artifactId, VersionRange.createFromVersion(""), Artifact.SCOPE_COMPILE, "pom", null, + new DefaultArtifactHandler("pom")); + ArtifactRepositoryLayout repositoryLayout = getComponent(ArtifactRepositoryLayout.class); + ArtifactRepository remoteRepository = new DefaultArtifactRepository( + "id", + remoteRepositoryUrl, + repositoryLayout, + new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN), + new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN)); + List versions = getComponent(ArtifactMetadataSource.class).retrieveAvailableVersions( + artifact, + new DefaultArtifactRepository( + "local", + getLocalRepositoryFile().getPath(), + repositoryLayout), + Collections.singletonList(remoteRepository)); + + List result = new ArrayList(); + for (Object version : versions) { + result.add(version.toString()); + } + return result; + } + catch (Exception e) { + Maven2ServerGlobals.getLogger().info(e); + } + return Collections.emptyList(); + } + private void setConsoleAndIndicator(MavenServerConsole console, MavenServerProgressIndicator indicator) { myConsoleWrapper.setWrappee(console); myCurrentIndicator = indicator; @@ -698,5 +736,9 @@ public class Maven2ServerEmbedderImpl extends MavenRemoteObject implements Maven throw rethrowException(e); } } + + private interface Executor { + T execute() throws Exception; + } } diff --git a/plugins/maven/maven3-server-common/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedder.java b/plugins/maven/maven3-server-common/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedder.java index 2a1e7beb5fef..fea70ad59126 100644 --- a/plugins/maven/maven3-server-common/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedder.java +++ b/plugins/maven/maven3-server-common/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedder.java @@ -39,25 +39,6 @@ public abstract class Maven3ServerEmbedder extends MavenRemoteObject implements initLog4J(settings); } - @Nullable - public String getMavenVersion() { - return MAVEN_VERSION; - } - - @SuppressWarnings({"unchecked"}) - public abstract T getComponent(Class clazz, String roleHint); - - @SuppressWarnings({"unchecked"}) - public abstract T getComponent(Class clazz); - - public abstract void executeWithMavenSession(MavenExecutionRequest request, Runnable runnable); - - public abstract MavenExecutionRequest createRequest(File file, - List activeProfiles, - List inactiveProfiles, - List goals) - throws RemoteException; - private static void initLog4J(MavenServerSettings settings) { try { BasicConfigurator.configure(); @@ -89,4 +70,23 @@ public abstract class Maven3ServerEmbedder extends MavenRemoteObject implements } return Level.INFO; } + + @Nullable + public String getMavenVersion() { + return MAVEN_VERSION; + } + + @SuppressWarnings({"unchecked"}) + public abstract T getComponent(Class clazz, String roleHint); + + @SuppressWarnings({"unchecked"}) + public abstract T getComponent(Class clazz); + + public abstract void executeWithMavenSession(MavenExecutionRequest request, Runnable runnable); + + public abstract MavenExecutionRequest createRequest(File file, + List activeProfiles, + List inactiveProfiles, + List goals) + throws RemoteException; } diff --git a/plugins/maven/maven30-server-impl/src/org/jetbrains/idea/maven/server/Maven30ServerEmbedderImpl.java b/plugins/maven/maven30-server-impl/src/org/jetbrains/idea/maven/server/Maven30ServerEmbedderImpl.java index f17e2aa0bdec..9bfa49a42b39 100644 --- a/plugins/maven/maven30-server-impl/src/org/jetbrains/idea/maven/server/Maven30ServerEmbedderImpl.java +++ b/plugins/maven/maven30-server-impl/src/org/jetbrains/idea/maven/server/Maven30ServerEmbedderImpl.java @@ -15,6 +15,9 @@ */ package org.jetbrains.idea.maven.server; +import com.google.common.base.Function; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.SystemProperties; @@ -22,13 +25,19 @@ import gnu.trove.THashMap; import gnu.trove.THashSet; import org.apache.maven.*; import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; +import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; +import org.apache.maven.artifact.repository.MavenArtifactRepository; +import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.artifact.repository.metadata.RepositoryMetadataManager; import org.apache.maven.artifact.resolver.*; +import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.cli.MavenCli; import org.apache.maven.execution.*; import org.apache.maven.model.Activation; @@ -247,6 +256,184 @@ public class Maven30ServerEmbedderImpl extends Maven3ServerEmbedder { return result; } + private static void warn(String message, Throwable e) { + try { + Maven3ServerGlobals.getLogger().warn(new RuntimeException(message, e)); + } + catch (RemoteException e1) { + throw new RuntimeException(e1); + } + } + + private static MavenExecutionResult handleException(Throwable e) { + if (e instanceof Error) throw (Error)e; + + return new MavenExecutionResult(null, Collections.singletonList((Exception)e)); + } + + private static Collection collectActivatedProfiles(MavenProject mavenProject) + throws RemoteException { + // for some reason project's active profiles do not contain parent's profiles - only local and settings'. + // parent's profiles do not contain settings' profiles. + + List profiles = new ArrayList(); + try { + while (mavenProject != null) { + profiles.addAll(mavenProject.getActiveProfiles()); + mavenProject = mavenProject.getParent(); + } + } + catch (Exception e) { + // don't bother user if maven failed to build parent project + Maven3ServerGlobals.getLogger().info(e); + } + return collectProfilesIds(profiles); + } + + private static List filterExceptions(List list) { + for (Throwable throwable : list) { + if (!(throwable instanceof Exception)) { + throw new RuntimeException(throwable); + } + } + + return (List)((List)list); + } + + public static MavenModel interpolateAndAlignModel(MavenModel model, File basedir) throws RemoteException { + Model result = MavenModelConverter.toNativeModel(model); + result = doInterpolate(result, basedir); + + PathTranslator pathTranslator = new DefaultPathTranslator(); + pathTranslator.alignToBaseDirectory(result, basedir); + + return MavenModelConverter.convertModel(result, null); + } + + public static MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) throws RemoteException { + Model result = MavenModelConverter.toNativeModel(model); + new DefaultModelInheritanceAssembler().assembleModelInheritance(result, MavenModelConverter.toNativeModel(parentModel)); + return MavenModelConverter.convertModel(result, null); + } + + public static ProfileApplicationResult applyProfiles(MavenModel model, + File basedir, + MavenExplicitProfiles explicitProfiles, + Collection alwaysOnProfiles) throws RemoteException { + Model nativeModel = MavenModelConverter.toNativeModel(model); + + Collection enabledProfiles = explicitProfiles.getEnabledProfiles(); + Collection disabledProfiles = explicitProfiles.getDisabledProfiles(); + List activatedPom = new ArrayList(); + List activatedExternal = new ArrayList(); + List activeByDefault = new ArrayList(); + + List rawProfiles = nativeModel.getProfiles(); + List expandedProfilesCache = null; + List deactivatedProfiles = new ArrayList(); + + for (int i = 0; i < rawProfiles.size(); i++) { + Profile eachRawProfile = rawProfiles.get(i); + + if (disabledProfiles.contains(eachRawProfile.getId())) { + deactivatedProfiles.add(eachRawProfile); + continue; + } + + boolean shouldAdd = enabledProfiles.contains(eachRawProfile.getId()) || alwaysOnProfiles.contains(eachRawProfile.getId()); + + Activation activation = eachRawProfile.getActivation(); + if (activation != null) { + if (activation.isActiveByDefault()) { + activeByDefault.add(eachRawProfile); + } + + // expand only if necessary + if (expandedProfilesCache == null) expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles(); + Profile eachExpandedProfile = expandedProfilesCache.get(i); + + for (ProfileActivator eachActivator : getProfileActivators(basedir)) { + try { + if (eachActivator.canDetermineActivation(eachExpandedProfile) && eachActivator.isActive(eachExpandedProfile)) { + shouldAdd = true; + break; + } + } + catch (ProfileActivationException e) { + Maven3ServerGlobals.getLogger().warn(e); + } + } + } + + if (shouldAdd) { + if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) { + activatedPom.add(eachRawProfile); + } + else { + activatedExternal.add(eachRawProfile); + } + } + } + + List activatedProfiles = new ArrayList(activatedPom.isEmpty() ? activeByDefault : activatedPom); + activatedProfiles.addAll(activatedExternal); + + for (Profile each : activatedProfiles) { + new DefaultProfileInjector().injectProfile(nativeModel, each, null, null); + } + + return new ProfileApplicationResult(MavenModelConverter.convertModel(nativeModel, null), + new MavenExplicitProfiles(collectProfilesIds(activatedProfiles), + collectProfilesIds(deactivatedProfiles)) + ); + } + + private static Model doInterpolate(Model result, File basedir) throws RemoteException { + try { + AbstractStringBasedModelInterpolator interpolator = new CustomMaven3ModelInterpolator(new DefaultPathTranslator()); + interpolator.initialize(); + + Properties props = MavenServerUtil.collectSystemProperties(); + ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(props); + config.setBuildStartTime(new Date()); + + result = interpolator.interpolate(result, basedir, config, false); + } + catch (ModelInterpolationException e) { + Maven3ServerGlobals.getLogger().warn(e); + } + catch (InitializationException e) { + Maven3ServerGlobals.getLogger().error(e); + } + return result; + } + + private static Collection collectProfilesIds(List profiles) { + Collection result = new THashSet(); + for (Profile each : profiles) { + if (each.getId() != null) { + result.add(each.getId()); + } + } + return result; + } + + private static ProfileActivator[] getProfileActivators(File basedir) throws RemoteException { + SystemPropertyProfileActivator sysPropertyActivator = new SystemPropertyProfileActivator(); + DefaultContext context = new DefaultContext(); + context.put("SystemProperties", MavenServerUtil.collectSystemProperties()); + try { + sysPropertyActivator.contextualize(context); + } + catch (ContextException e) { + Maven3ServerGlobals.getLogger().error(e); + return new ProfileActivator[0]; + } + + return new ProfileActivator[]{new MyFileProfileActivator(basedir), sysPropertyActivator, new JdkPrefixProfileActivator(), + new OperatingSystemProfileActivator()}; + } + @SuppressWarnings({"unchecked"}) public T getComponent(Class clazz, String roleHint) { try { @@ -605,15 +792,6 @@ public class Maven30ServerEmbedderImpl extends Maven3ServerEmbedder { return lifecycleListeners; } - private static void warn(String message, Throwable e) { - try { - Maven3ServerGlobals.getLogger().warn(new RuntimeException(message, e)); - } - catch (RemoteException e1) { - throw new RuntimeException(e1); - } - } - public MavenExecutionRequest createRequest(File file, List activeProfiles, List inactiveProfiles, List goals) throws RemoteException { //Properties executionProperties = myMavenSettings.getProperties(); @@ -646,12 +824,6 @@ public class Maven30ServerEmbedderImpl extends Maven3ServerEmbedder { } } - private static MavenExecutionResult handleException(Throwable e) { - if (e instanceof Error) throw (Error)e; - - return new MavenExecutionResult(null, Collections.singletonList((Exception)e)); - } - @NotNull public File getLocalRepositoryFile() { return new File(myLocalRepository.getBasedir()); @@ -709,26 +881,6 @@ public class Maven30ServerEmbedderImpl extends Maven3ServerEmbedder { return new MavenServerExecutionResult(data, problems, unresolvedArtifacts); } - private static Collection collectActivatedProfiles(MavenProject mavenProject) - throws RemoteException { - // for some reason project's active profiles do not contain parent's profiles - only local and settings'. - // parent's profiles do not contain settings' profiles. - - List profiles = new ArrayList(); - try { - while (mavenProject != null) { - profiles.addAll(mavenProject.getActiveProfiles()); - mavenProject = mavenProject.getParent(); - } - } - catch (Exception e) { - // don't bother user if maven failed to build parent project - Maven3ServerGlobals.getLogger().info(e); - } - return collectProfilesIds(profiles); - } - - private void validate(@NotNull File file, @NotNull Collection exceptions, @NotNull Collection problems, @@ -965,16 +1117,6 @@ public class Maven30ServerEmbedderImpl extends Maven3ServerEmbedder { return result; } - private static List filterExceptions(List list) { - for (Throwable throwable : list) { - if (!(throwable instanceof Exception)) { - throw new RuntimeException(throwable); - } - } - - return (List)((List)list); - } - @Override public void reset() throws RemoteException { try { @@ -1003,138 +1145,32 @@ public class Maven30ServerEmbedderImpl extends Maven3ServerEmbedder { // do nothing } - public static MavenModel interpolateAndAlignModel(MavenModel model, File basedir) throws RemoteException { - Model result = MavenModelConverter.toNativeModel(model); - result = doInterpolate(result, basedir); - - PathTranslator pathTranslator = new DefaultPathTranslator(); - pathTranslator.alignToBaseDirectory(result, basedir); - - return MavenModelConverter.convertModel(result, null); - } - - public static MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) throws RemoteException { - Model result = MavenModelConverter.toNativeModel(model); - new DefaultModelInheritanceAssembler().assembleModelInheritance(result, MavenModelConverter.toNativeModel(parentModel)); - return MavenModelConverter.convertModel(result, null); - } - - public static ProfileApplicationResult applyProfiles(MavenModel model, - File basedir, - MavenExplicitProfiles explicitProfiles, - Collection alwaysOnProfiles) throws RemoteException { - Model nativeModel = MavenModelConverter.toNativeModel(model); - - Collection enabledProfiles = explicitProfiles.getEnabledProfiles(); - Collection disabledProfiles = explicitProfiles.getDisabledProfiles(); - List activatedPom = new ArrayList(); - List activatedExternal = new ArrayList(); - List activeByDefault = new ArrayList(); - - List rawProfiles = nativeModel.getProfiles(); - List expandedProfilesCache = null; - List deactivatedProfiles = new ArrayList(); - - for (int i = 0; i < rawProfiles.size(); i++) { - Profile eachRawProfile = rawProfiles.get(i); - - if (disabledProfiles.contains(eachRawProfile.getId())) { - deactivatedProfiles.add(eachRawProfile); - continue; - } - - boolean shouldAdd = enabledProfiles.contains(eachRawProfile.getId()) || alwaysOnProfiles.contains(eachRawProfile.getId()); - - Activation activation = eachRawProfile.getActivation(); - if (activation != null) { - if (activation.isActiveByDefault()) { - activeByDefault.add(eachRawProfile); - } - - // expand only if necessary - if (expandedProfilesCache == null) expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles(); - Profile eachExpandedProfile = expandedProfilesCache.get(i); - - for (ProfileActivator eachActivator : getProfileActivators(basedir)) { - try { - if (eachActivator.canDetermineActivation(eachExpandedProfile) && eachActivator.isActive(eachExpandedProfile)) { - shouldAdd = true; - break; - } - } - catch (ProfileActivationException e) { - Maven3ServerGlobals.getLogger().warn(e); - } - } - } - - if (shouldAdd) { - if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) { - activatedPom.add(eachRawProfile); - } - else { - activatedExternal.add(eachRawProfile); - } - } - } - - List activatedProfiles = new ArrayList(activatedPom.isEmpty() ? activeByDefault : activatedPom); - activatedProfiles.addAll(activatedExternal); - - for (Profile each : activatedProfiles) { - new DefaultProfileInjector().injectProfile(nativeModel, each, null, null); - } - - return new ProfileApplicationResult(MavenModelConverter.convertModel(nativeModel, null), - new MavenExplicitProfiles(collectProfilesIds(activatedProfiles), - collectProfilesIds(deactivatedProfiles)) - ); - } - - private static Model doInterpolate(Model result, File basedir) throws RemoteException { + @NotNull + @Override + public List retrieveAvailableVersions(@NotNull String groupId, @NotNull String artifactId, @NotNull String remoteRepositoryUrl) + throws RemoteException { try { - AbstractStringBasedModelInterpolator interpolator = new CustomMaven3ModelInterpolator(new DefaultPathTranslator()); - interpolator.initialize(); - - Properties props = MavenServerUtil.collectSystemProperties(); - ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(props); - config.setBuildStartTime(new Date()); - - result = interpolator.interpolate(result, basedir, config, false); + Artifact artifact = + new DefaultArtifact(groupId, artifactId, "", Artifact.SCOPE_COMPILE, "pom", null, new DefaultArtifactHandler("pom")); + ArtifactRepository remoteRepository = new MavenArtifactRepository( + "id", + remoteRepositoryUrl, + getComponent(ArtifactRepositoryLayout.class), + new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN), + new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN)); + List versions = getComponent(ArtifactMetadataSource.class) + .retrieveAvailableVersions(artifact, myLocalRepository, Collections.singletonList(remoteRepository)); + return Lists.newArrayList(Iterables.transform(versions, new Function() { + @Override + public String apply(ArtifactVersion version) { + return version.toString(); + } + })); } - catch (ModelInterpolationException e) { - Maven3ServerGlobals.getLogger().warn(e); + catch (Exception e) { + Maven3ServerGlobals.getLogger().info(e); } - catch (InitializationException e) { - Maven3ServerGlobals.getLogger().error(e); - } - return result; - } - - private static Collection collectProfilesIds(List profiles) { - Collection result = new THashSet(); - for (Profile each : profiles) { - if (each.getId() != null) { - result.add(each.getId()); - } - } - return result; - } - - private static ProfileActivator[] getProfileActivators(File basedir) throws RemoteException { - SystemPropertyProfileActivator sysPropertyActivator = new SystemPropertyProfileActivator(); - DefaultContext context = new DefaultContext(); - context.put("SystemProperties", MavenServerUtil.collectSystemProperties()); - try { - sysPropertyActivator.contextualize(context); - } - catch (ContextException e) { - Maven3ServerGlobals.getLogger().error(e); - return new ProfileActivator[0]; - } - - return new ProfileActivator[]{new MyFileProfileActivator(basedir), sysPropertyActivator, new JdkPrefixProfileActivator(), - new OperatingSystemProfileActivator()}; + return Collections.emptyList(); } public interface Computable { diff --git a/plugins/maven/maven32-server-impl/maven32-server-impl.iml b/plugins/maven/maven32-server-impl/maven32-server-impl.iml index 6543afc8ba79..f1c40dd8f88b 100644 --- a/plugins/maven/maven32-server-impl/maven32-server-impl.iml +++ b/plugins/maven/maven32-server-impl/maven32-server-impl.iml @@ -18,7 +18,9 @@ - + + + @@ -73,5 +75,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/plugins/maven/maven32-server-impl/src/org/jetbrains/idea/maven/server/Maven32ServerEmbedderImpl.java b/plugins/maven/maven32-server-impl/src/org/jetbrains/idea/maven/server/Maven32ServerEmbedderImpl.java index 7a4de3ae87f0..cacf237a1cab 100644 --- a/plugins/maven/maven32-server-impl/src/org/jetbrains/idea/maven/server/Maven32ServerEmbedderImpl.java +++ b/plugins/maven/maven32-server-impl/src/org/jetbrains/idea/maven/server/Maven32ServerEmbedderImpl.java @@ -15,6 +15,9 @@ */ package org.jetbrains.idea.maven.server; +import com.google.common.base.Function; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; @@ -24,13 +27,19 @@ import gnu.trove.THashMap; import gnu.trove.THashSet; import org.apache.maven.*; import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; +import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; +import org.apache.maven.artifact.repository.MavenArtifactRepository; +import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.artifact.repository.metadata.RepositoryMetadataManager; import org.apache.maven.artifact.resolver.*; +import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.cli.MavenCli; import org.apache.maven.execution.*; import org.apache.maven.model.Activation; @@ -262,6 +271,184 @@ public class Maven32ServerEmbedderImpl extends Maven3ServerEmbedder { return result; } + private static void warn(String message, Throwable e) { + try { + Maven3ServerGlobals.getLogger().warn(new RuntimeException(message, e)); + } + catch (RemoteException e1) { + throw new RuntimeException(e1); + } + } + + private static MavenExecutionResult handleException(Throwable e) { + if (e instanceof Error) throw (Error)e; + + return new MavenExecutionResult(null, Collections.singletonList((Exception)e)); + } + + private static Collection collectActivatedProfiles(MavenProject mavenProject) + throws RemoteException { + // for some reason project's active profiles do not contain parent's profiles - only local and settings'. + // parent's profiles do not contain settings' profiles. + + List profiles = new ArrayList(); + try { + while (mavenProject != null) { + profiles.addAll(mavenProject.getActiveProfiles()); + mavenProject = mavenProject.getParent(); + } + } + catch (Exception e) { + // don't bother user if maven failed to build parent project + Maven3ServerGlobals.getLogger().info(e); + } + return collectProfilesIds(profiles); + } + + private static List filterExceptions(List list) { + for (Throwable throwable : list) { + if (!(throwable instanceof Exception)) { + throw new RuntimeException(throwable); + } + } + + return (List)((List)list); + } + + public static MavenModel interpolateAndAlignModel(MavenModel model, File basedir) throws RemoteException { + Model result = MavenModelConverter.toNativeModel(model); + result = doInterpolate(result, basedir); + + PathTranslator pathTranslator = new DefaultPathTranslator(); + pathTranslator.alignToBaseDirectory(result, basedir); + + return MavenModelConverter.convertModel(result, null); + } + + public static MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) throws RemoteException { + Model result = MavenModelConverter.toNativeModel(model); + new DefaultModelInheritanceAssembler().assembleModelInheritance(result, MavenModelConverter.toNativeModel(parentModel)); + return MavenModelConverter.convertModel(result, null); + } + + public static ProfileApplicationResult applyProfiles(MavenModel model, + File basedir, + MavenExplicitProfiles explicitProfiles, + Collection alwaysOnProfiles) throws RemoteException { + Model nativeModel = MavenModelConverter.toNativeModel(model); + + Collection enabledProfiles = explicitProfiles.getEnabledProfiles(); + Collection disabledProfiles = explicitProfiles.getDisabledProfiles(); + List activatedPom = new ArrayList(); + List activatedExternal = new ArrayList(); + List activeByDefault = new ArrayList(); + + List rawProfiles = nativeModel.getProfiles(); + List expandedProfilesCache = null; + List deactivatedProfiles = new ArrayList(); + + for (int i = 0; i < rawProfiles.size(); i++) { + Profile eachRawProfile = rawProfiles.get(i); + + if (disabledProfiles.contains(eachRawProfile.getId())) { + deactivatedProfiles.add(eachRawProfile); + continue; + } + + boolean shouldAdd = enabledProfiles.contains(eachRawProfile.getId()) || alwaysOnProfiles.contains(eachRawProfile.getId()); + + Activation activation = eachRawProfile.getActivation(); + if (activation != null) { + if (activation.isActiveByDefault()) { + activeByDefault.add(eachRawProfile); + } + + // expand only if necessary + if (expandedProfilesCache == null) expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles(); + Profile eachExpandedProfile = expandedProfilesCache.get(i); + + for (ProfileActivator eachActivator : getProfileActivators(basedir)) { + try { + if (eachActivator.canDetermineActivation(eachExpandedProfile) && eachActivator.isActive(eachExpandedProfile)) { + shouldAdd = true; + break; + } + } + catch (ProfileActivationException e) { + Maven3ServerGlobals.getLogger().warn(e); + } + } + } + + if (shouldAdd) { + if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) { + activatedPom.add(eachRawProfile); + } + else { + activatedExternal.add(eachRawProfile); + } + } + } + + List activatedProfiles = new ArrayList(activatedPom.isEmpty() ? activeByDefault : activatedPom); + activatedProfiles.addAll(activatedExternal); + + for (Profile each : activatedProfiles) { + new DefaultProfileInjector().injectProfile(nativeModel, each, null, null); + } + + return new ProfileApplicationResult(MavenModelConverter.convertModel(nativeModel, null), + new MavenExplicitProfiles(collectProfilesIds(activatedProfiles), + collectProfilesIds(deactivatedProfiles)) + ); + } + + private static Model doInterpolate(Model result, File basedir) throws RemoteException { + try { + AbstractStringBasedModelInterpolator interpolator = new CustomMaven3ModelInterpolator(new DefaultPathTranslator()); + interpolator.initialize(); + + Properties props = MavenServerUtil.collectSystemProperties(); + ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(props); + config.setBuildStartTime(new Date()); + + result = interpolator.interpolate(result, basedir, config, false); + } + catch (ModelInterpolationException e) { + Maven3ServerGlobals.getLogger().warn(e); + } + catch (InitializationException e) { + Maven3ServerGlobals.getLogger().error(e); + } + return result; + } + + private static Collection collectProfilesIds(List profiles) { + Collection result = new THashSet(); + for (Profile each : profiles) { + if (each.getId() != null) { + result.add(each.getId()); + } + } + return result; + } + + private static ProfileActivator[] getProfileActivators(File basedir) throws RemoteException { + SystemPropertyProfileActivator sysPropertyActivator = new SystemPropertyProfileActivator(); + DefaultContext context = new DefaultContext(); + context.put("SystemProperties", MavenServerUtil.collectSystemProperties()); + try { + sysPropertyActivator.contextualize(context); + } + catch (ContextException e) { + Maven3ServerGlobals.getLogger().error(e); + return new ProfileActivator[0]; + } + + return new ProfileActivator[]{new MyFileProfileActivator(basedir), sysPropertyActivator, new JdkPrefixProfileActivator(), + new OperatingSystemProfileActivator()}; + } + @SuppressWarnings({"unchecked"}) public T getComponent(Class clazz, String roleHint) { try { @@ -620,15 +807,6 @@ public class Maven32ServerEmbedderImpl extends Maven3ServerEmbedder { return lifecycleListeners; } - private static void warn(String message, Throwable e) { - try { - Maven3ServerGlobals.getLogger().warn(new RuntimeException(message, e)); - } - catch (RemoteException e1) { - throw new RuntimeException(e1); - } - } - public MavenExecutionRequest createRequest(File file, List activeProfiles, List inactiveProfiles, List goals) throws RemoteException { //Properties executionProperties = myMavenSettings.getProperties(); @@ -675,12 +853,6 @@ public class Maven32ServerEmbedderImpl extends Maven3ServerEmbedder { } } - private static MavenExecutionResult handleException(Throwable e) { - if (e instanceof Error) throw (Error)e; - - return new MavenExecutionResult(null, Collections.singletonList((Exception)e)); - } - @NotNull public File getLocalRepositoryFile() { return new File(myLocalRepository.getBasedir()); @@ -738,26 +910,6 @@ public class Maven32ServerEmbedderImpl extends Maven3ServerEmbedder { return new MavenServerExecutionResult(data, problems, unresolvedArtifacts); } - private static Collection collectActivatedProfiles(MavenProject mavenProject) - throws RemoteException { - // for some reason project's active profiles do not contain parent's profiles - only local and settings'. - // parent's profiles do not contain settings' profiles. - - List profiles = new ArrayList(); - try { - while (mavenProject != null) { - profiles.addAll(mavenProject.getActiveProfiles()); - mavenProject = mavenProject.getParent(); - } - } - catch (Exception e) { - // don't bother user if maven failed to build parent project - Maven3ServerGlobals.getLogger().info(e); - } - return collectProfilesIds(profiles); - } - - private void validate(@NotNull File file, @NotNull Collection exceptions, @NotNull Collection problems, @@ -1032,16 +1184,6 @@ public class Maven32ServerEmbedderImpl extends Maven3ServerEmbedder { return result; } - private static List filterExceptions(List list) { - for (Throwable throwable : list) { - if (!(throwable instanceof Exception)) { - throw new RuntimeException(throwable); - } - } - - return (List)((List)list); - } - @Override public void reset() throws RemoteException { try { @@ -1070,138 +1212,32 @@ public class Maven32ServerEmbedderImpl extends Maven3ServerEmbedder { // do nothing } - public static MavenModel interpolateAndAlignModel(MavenModel model, File basedir) throws RemoteException { - Model result = MavenModelConverter.toNativeModel(model); - result = doInterpolate(result, basedir); - - PathTranslator pathTranslator = new DefaultPathTranslator(); - pathTranslator.alignToBaseDirectory(result, basedir); - - return MavenModelConverter.convertModel(result, null); - } - - public static MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) throws RemoteException { - Model result = MavenModelConverter.toNativeModel(model); - new DefaultModelInheritanceAssembler().assembleModelInheritance(result, MavenModelConverter.toNativeModel(parentModel)); - return MavenModelConverter.convertModel(result, null); - } - - public static ProfileApplicationResult applyProfiles(MavenModel model, - File basedir, - MavenExplicitProfiles explicitProfiles, - Collection alwaysOnProfiles) throws RemoteException { - Model nativeModel = MavenModelConverter.toNativeModel(model); - - Collection enabledProfiles = explicitProfiles.getEnabledProfiles(); - Collection disabledProfiles = explicitProfiles.getDisabledProfiles(); - List activatedPom = new ArrayList(); - List activatedExternal = new ArrayList(); - List activeByDefault = new ArrayList(); - - List rawProfiles = nativeModel.getProfiles(); - List expandedProfilesCache = null; - List deactivatedProfiles = new ArrayList(); - - for (int i = 0; i < rawProfiles.size(); i++) { - Profile eachRawProfile = rawProfiles.get(i); - - if (disabledProfiles.contains(eachRawProfile.getId())) { - deactivatedProfiles.add(eachRawProfile); - continue; - } - - boolean shouldAdd = enabledProfiles.contains(eachRawProfile.getId()) || alwaysOnProfiles.contains(eachRawProfile.getId()); - - Activation activation = eachRawProfile.getActivation(); - if (activation != null) { - if (activation.isActiveByDefault()) { - activeByDefault.add(eachRawProfile); - } - - // expand only if necessary - if (expandedProfilesCache == null) expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles(); - Profile eachExpandedProfile = expandedProfilesCache.get(i); - - for (ProfileActivator eachActivator : getProfileActivators(basedir)) { - try { - if (eachActivator.canDetermineActivation(eachExpandedProfile) && eachActivator.isActive(eachExpandedProfile)) { - shouldAdd = true; - break; - } - } - catch (ProfileActivationException e) { - Maven3ServerGlobals.getLogger().warn(e); - } - } - } - - if (shouldAdd) { - if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) { - activatedPom.add(eachRawProfile); - } - else { - activatedExternal.add(eachRawProfile); - } - } - } - - List activatedProfiles = new ArrayList(activatedPom.isEmpty() ? activeByDefault : activatedPom); - activatedProfiles.addAll(activatedExternal); - - for (Profile each : activatedProfiles) { - new DefaultProfileInjector().injectProfile(nativeModel, each, null, null); - } - - return new ProfileApplicationResult(MavenModelConverter.convertModel(nativeModel, null), - new MavenExplicitProfiles(collectProfilesIds(activatedProfiles), - collectProfilesIds(deactivatedProfiles)) - ); - } - - private static Model doInterpolate(Model result, File basedir) throws RemoteException { + @NotNull + @Override + public List retrieveAvailableVersions(@NotNull String groupId, @NotNull String artifactId, @NotNull String remoteRepositoryUrl) + throws RemoteException { try { - AbstractStringBasedModelInterpolator interpolator = new CustomMaven3ModelInterpolator(new DefaultPathTranslator()); - interpolator.initialize(); - - Properties props = MavenServerUtil.collectSystemProperties(); - ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(props); - config.setBuildStartTime(new Date()); - - result = interpolator.interpolate(result, basedir, config, false); + Artifact artifact = + new DefaultArtifact(groupId, artifactId, "", Artifact.SCOPE_COMPILE, "pom", null, new DefaultArtifactHandler("pom")); + ArtifactRepository remoteRepository = new MavenArtifactRepository( + "id", + remoteRepositoryUrl, + getComponent(ArtifactRepositoryLayout.class), + new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN), + new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN)); + List versions = getComponent(ArtifactMetadataSource.class) + .retrieveAvailableVersions(artifact, myLocalRepository, Collections.singletonList(remoteRepository)); + return Lists.newArrayList(Iterables.transform(versions, new Function() { + @Override + public String apply(ArtifactVersion version) { + return version.toString(); + } + })); } - catch (ModelInterpolationException e) { - Maven3ServerGlobals.getLogger().warn(e); + catch (Exception e) { + Maven3ServerGlobals.getLogger().info(e); } - catch (InitializationException e) { - Maven3ServerGlobals.getLogger().error(e); - } - return result; - } - - private static Collection collectProfilesIds(List profiles) { - Collection result = new THashSet(); - for (Profile each : profiles) { - if (each.getId() != null) { - result.add(each.getId()); - } - } - return result; - } - - private static ProfileActivator[] getProfileActivators(File basedir) throws RemoteException { - SystemPropertyProfileActivator sysPropertyActivator = new SystemPropertyProfileActivator(); - DefaultContext context = new DefaultContext(); - context.put("SystemProperties", MavenServerUtil.collectSystemProperties()); - try { - sysPropertyActivator.contextualize(context); - } - catch (ContextException e) { - Maven3ServerGlobals.getLogger().error(e); - return new ProfileActivator[0]; - } - - return new ProfileActivator[]{new MyFileProfileActivator(basedir), sysPropertyActivator, new JdkPrefixProfileActivator(), - new OperatingSystemProfileActivator()}; + return Collections.emptyList(); } public interface Computable { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java index 006f4caeac3a..9f6bd2f97532 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenEmbedderWrapper.java @@ -141,6 +141,19 @@ public abstract class MavenEmbedderWrapper extends RemoteObjectWrapper retrieveVersions(@NotNull final String groupId, + @NotNull final String artifactId, + @NotNull final String remoteRepository) throws MavenProcessCanceledException { + + return perform(new RetriableCancelable>() { + @Override + public List execute() throws RemoteException, MavenServerProcessCanceledException { + return getOrCreateWrappee().retrieveAvailableVersions(groupId, artifactId, remoteRepository); + } + }); + } + public Collection resolvePlugin(@NotNull final MavenPlugin plugin, @NotNull final List repositories, @NotNull final NativeMavenProjectHolder nativeMavenProject, diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAttachHandler.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAttachHandler.java index e7a676283be6..3f7adc5f0c1a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAttachHandler.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/library/RepositoryAttachHandler.java @@ -37,6 +37,7 @@ import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; @@ -346,6 +347,30 @@ public class RepositoryAttachHandler { doResolveInner(project, Collections.singletonList(mavenId), extraTypes, repositories, resultProcessor, indicator); } + public static List retrieveVersions(@NotNull final Project project, + @NotNull final String groupId, + @NotNull final String artifactId, + @NotNull final String remoteRepository) { + MavenEmbeddersManager manager = MavenProjectsManager.getInstance(project).getEmbeddersManager(); + MavenEmbedderWrapper embedder = manager.getEmbedder(MavenEmbeddersManager.FOR_DOWNLOAD); + try { + List versions = embedder.retrieveVersions(groupId, artifactId, remoteRepository); + Collections.sort(versions, new Comparator() { + @Override + public int compare(String o1, String o2) { + return StringUtil.compareVersionNumbers(o2, o1); + } + }); + return versions; + } + catch (MavenProcessCanceledException e) { + return Collections.emptyList(); + } + finally { + manager.release(embedder); + } + } + public static void doResolveInner(Project project, List mavenIds, List extraTypes, From 8ea453e66ad83261bb07095ec6c02492f9b67103 Mon Sep 17 00:00:00 2001 From: Eugene Zhuravlev Date: Mon, 20 Jul 2015 13:57:47 +0200 Subject: [PATCH 029/106] post-review: rewrite FilesDelta public api to avoid possible deadlocks --- .../jps/incremental/fs/BuildFSState.java | 7 ++--- .../jps/incremental/fs/FilesDelta.java | 27 ++++++++++--------- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/BuildFSState.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/BuildFSState.java index 21b193f13786..8b59df6dcb61 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/BuildFSState.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/BuildFSState.java @@ -18,6 +18,7 @@ package org.jetbrains.jps.incremental.fs; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileSystemUtil; +import com.intellij.util.SmartList; import com.intellij.util.containers.MultiMap; import com.intellij.util.io.IOUtil; import org.jetbrains.annotations.NotNull; @@ -267,11 +268,11 @@ public class BuildFSState { if (currentDelta == null) { // this is the initial round. // Need to make a snapshot of the FS state so that all builders in the chain see the same picture - currentDelta = new FilesDelta(); + final List deltas = new SmartList(); for (ModuleBuildTarget target : chunk.getTargets()) { - final FilesDelta targetDelta = getDelta(target); - currentDelta.addAll(targetDelta); + deltas.add(getDelta(target)); } + currentDelta = new FilesDelta(deltas); } setRoundDelta(CURRENT_ROUND_DELTA_KEY, context, currentDelta); setRoundDelta(NEXT_ROUND_DELTA_KEY, context, new FilesDelta()); diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/FilesDelta.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/FilesDelta.java index bcd48f67a834..5d7f067a06eb 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/FilesDelta.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/FilesDelta.java @@ -49,22 +49,25 @@ public final class FilesDelta { myDataLock.unlock(); } - protected void addAll(FilesDelta other) { - lockData(); + public FilesDelta() { + } + + FilesDelta(Collection deltas) { + for (FilesDelta delta : deltas) { + addAll(delta); + } + } + + private void addAll(FilesDelta other) { + other.lockData(); try { - other.lockData(); - try { - myDeletedPaths.addAll(other.myDeletedPaths); - for (Map.Entry> entry : other.myFilesToRecompile.entrySet()) { - _addToRecompiled(entry.getKey(), entry.getValue()); - } - } - finally { - other.unlockData(); + myDeletedPaths.addAll(other.myDeletedPaths); + for (Map.Entry> entry : other.myFilesToRecompile.entrySet()) { + _addToRecompiled(entry.getKey(), entry.getValue()); } } finally { - unlockData(); + other.unlockData(); } } From 9140c5420fa72065c542942686f3faca41f3acba Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Thu, 16 Jul 2015 17:20:28 +0300 Subject: [PATCH 030/106] cleanup --- .../daemon/LightAdvHighlightingTest.java | 40 ++++++++----------- .../impl/TrailingSpacesStripperTest.java | 2 +- 2 files changed, 18 insertions(+), 24 deletions(-) diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java index 832290d5d733..f96c4dd6a37a 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -281,20 +281,17 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase { } public void testUnusedInspectionNonPrivateMembersReferencedFromText() { doTest(true, false); - WriteCommandAction.runWriteCommandAction(null, new Runnable() { - @Override - public void run() { - PsiDirectory directory = myFile.getParent(); - assertNotNull(myFile.toString(), directory); - PsiFile txt = directory.createFile("x.txt"); - VirtualFile vFile = txt.getVirtualFile(); - assertNotNull(txt.toString(), vFile); - try { - VfsUtil.saveText(vFile, "XXX"); - } - catch (IOException e) { - throw new RuntimeException(e); - } + WriteCommandAction.runWriteCommandAction(null, () -> { + PsiDirectory directory = myFile.getParent(); + assertNotNull(myFile.toString(), directory); + PsiFile txt = directory.createFile("x.txt"); + VirtualFile vFile = txt.getVirtualFile(); + assertNotNull(txt.toString(), vFile); + try { + VfsUtil.saveText(vFile, "XXX"); + } + catch (IOException e) { + throw new RuntimeException(e); } }); @@ -311,7 +308,7 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase { doTestFile(BASE_PATH + "/" + getTestName(false) + ".java").checkSymbolNames().test(); } - public static class MyAnnotator implements Annotator { + private static class MyAnnotator implements Annotator { @Override public void annotate(@NotNull PsiElement psiElement, @NotNull final AnnotationHolder holder) { psiElement.accept(new XmlElementVisitor() { @@ -358,12 +355,9 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase { final String hugeExpr = sb.toString(); final int pos = getEditor().getDocument().getText().indexOf("\"\""); - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - getEditor().getDocument().replaceString(pos, pos + 2, hugeExpr); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - } + ApplicationManager.getApplication().runWriteAction(() -> { + getEditor().getDocument().replaceString(pos, pos + 2, hugeExpr); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); }); final PsiField field = ((PsiJavaFile)getFile()).getClasses()[0].getFields()[0]; @@ -406,7 +400,7 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase { assertTrue(!infos.isEmpty()); } - public static class MyTopFileAnnotator implements Annotator { + private static class MyTopFileAnnotator implements Annotator { @Override public void annotate(@NotNull PsiElement psiElement, @NotNull final AnnotationHolder holder) { if (psiElement instanceof PsiFile && !psiElement.getText().contains("xxx")) { diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/TrailingSpacesStripperTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/TrailingSpacesStripperTest.java index 8c974641663e..269ff6b7427d 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/TrailingSpacesStripperTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/TrailingSpacesStripperTest.java @@ -116,7 +116,7 @@ public class TrailingSpacesStripperTest extends LightPlatformCodeInsightTestCase public void testOnlyModifiedLinesWhenDoesNotAllowCaretAfterEndOfLine() throws IOException { configureFromFileText("x.txt", "xxx \nZ "); type(' '); - myEditor.getCaretModel().moveToOffset(myEditor.getDocument().getText().indexOf("Z") + 1); + myEditor.getCaretModel().moveToOffset(myEditor.getDocument().getText().indexOf('Z') + 1); type('Z'); stripTrailingSpaces(); From 46454dac73719de3ca86491537fee6d420960ed8 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Thu, 16 Jul 2015 19:51:18 +0300 Subject: [PATCH 031/106] reverted --- .../codeInsight/daemon/LightAdvHighlightingTest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java index f96c4dd6a37a..6c788303243e 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java @@ -308,7 +308,8 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase { doTestFile(BASE_PATH + "/" + getTestName(false) + ".java").checkSymbolNames().test(); } - private static class MyAnnotator implements Annotator { + // must stay public for picocontainer to work + public static class MyAnnotator implements Annotator { @Override public void annotate(@NotNull PsiElement psiElement, @NotNull final AnnotationHolder holder) { psiElement.accept(new XmlElementVisitor() { @@ -400,7 +401,8 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase { assertTrue(!infos.isEmpty()); } - private static class MyTopFileAnnotator implements Annotator { + // must stay public for picocontainer to work + public static class MyTopFileAnnotator implements Annotator { @Override public void annotate(@NotNull PsiElement psiElement, @NotNull final AnnotationHolder holder) { if (psiElement instanceof PsiFile && !psiElement.getText().contains("xxx")) { From 91b9f4c199be3593fd91cc68f27d295f6476da71 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Mon, 20 Jul 2015 14:46:44 +0300 Subject: [PATCH 032/106] EA-70499 - CCE: PersistentFSImpl.findFileById --- .../openapi/vfs/newvfs/persistent/PersistentFSImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java index 1422d3b27fe8..17feca44f204 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java @@ -978,8 +978,8 @@ public class PersistentFSImpl extends PersistentFS implements ApplicationCompone VirtualFileSystemEntry result = myIdToDirCache.get(parentId); for (int i=parents.size() - 2; i>=0; i--) { - if (result == null) { - break; + if (!(result instanceof VirtualDirectoryImpl)) { + return null; } parentId = parents.get(i); result = ((VirtualDirectoryImpl)result).findChildById(parentId, cachedOnly); From 420a01d4922e03939c7f2c70cce3727679b57466 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Mon, 20 Jul 2015 14:50:37 +0300 Subject: [PATCH 033/106] do not update actions in EDT (IDEA-142089) --- .../codeInsight/CodeInsightTestCase.java | 8 +++++++- .../daemon/impl/ShowIntentionsPass.java | 3 --- .../impl/IntentionHintComponent.java | 2 +- .../intention/impl/IntentionListStep.java | 19 ++++++++++--------- 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java index 9119a4d1ca6f..95cda3a3982f 100644 --- a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java @@ -568,10 +568,16 @@ public abstract class CodeInsightTestCase extends PsiTestCase { undoManager.undo(textEditor); } + protected void caretLeft() { + caretRight(getEditor()); + } + protected void caretLeft(@NotNull Editor editor) { + LightPlatformCodeInsightTestCase.executeAction(IdeActions.ACTION_EDITOR_MOVE_CARET_LEFT, editor, getProject()); + } protected void caretRight() { caretRight(getEditor()); } - protected void caretRight(Editor editor) { + protected void caretRight(@NotNull Editor editor) { LightPlatformCodeInsightTestCase.executeAction(IdeActions.ACTION_EDITOR_MOVE_CARET_RIGHT, editor, getProject()); } protected void caretUp() { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java index cf5cd367a25e..f00c379d2b53 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java @@ -258,9 +258,6 @@ public class ShowIntentionsPass extends TextEditorHighlightingPass { else if (result == IntentionHintComponent.PopupUpdateResult.CHANGED_INVISIBLE) { myHasToRecreate = true; } - else { - myShowBulb = false; // nothing to apply - } } public static void getActionsToShow(@NotNull final Editor hostEditor, diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java index 2e121b74a118..53c2069444e5 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java @@ -219,7 +219,7 @@ public class IntentionHintComponent implements Disposable, ScrollAwareHint { return PopupUpdateResult.HIDE_AND_RECREATE; } IntentionListStep step = (IntentionListStep)myPopup.getListStep(); - if (!step.updateActions(intentions)) { + if (!step.wrapAndUpdateActions(intentions, true)) { return PopupUpdateResult.NOTHING_CHANGED; } if (!myPopupShown) { 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 f9717dda2df0..6bc0bfef71f7 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 @@ -87,7 +87,7 @@ class IntentionListStep implements ListPopupStep @NotNull PsiFile file, @NotNull Project project) { this(intentionHintComponent, editor, file, project); - updateActions(intentions); + wrapAndUpdateActions(intentions, false); // when create bulb do not update actions again since it would impede the EDT } IntentionListStep(@Nullable IntentionHintComponent intentionHintComponent, @@ -102,16 +102,17 @@ class IntentionListStep implements ListPopupStep } //true if something changed - boolean updateActions(@NotNull ShowIntentionsPass.IntentionsInfo intentions) { - boolean changed = wrapActionsTo(intentions.errorFixesToShow, myCachedErrorFixes); - changed |= wrapActionsTo(intentions.inspectionFixesToShow, myCachedInspectionFixes); - changed |= wrapActionsTo(intentions.intentionsToShow, myCachedIntentions); - changed |= wrapActionsTo(intentions.guttersToShow, myCachedGutters); + boolean wrapAndUpdateActions(@NotNull ShowIntentionsPass.IntentionsInfo intentions, boolean callUpdate) { + boolean changed = wrapActionsTo(intentions.errorFixesToShow, myCachedErrorFixes, callUpdate); + changed |= wrapActionsTo(intentions.inspectionFixesToShow, myCachedInspectionFixes, callUpdate); + changed |= wrapActionsTo(intentions.intentionsToShow, myCachedIntentions, callUpdate); + changed |= wrapActionsTo(intentions.guttersToShow, myCachedGutters, callUpdate); return changed; } private boolean wrapActionsTo(@NotNull List newDescriptors, - @NotNull Set cachedActions) { + @NotNull Set cachedActions, + boolean callUpdate) { final int caretOffset = myEditor.getCaretModel().getOffset(); final int fileOffset = caretOffset > 0 && caretOffset == myFile.getTextLength() ? caretOffset - 1 : caretOffset; PsiElement element; @@ -154,12 +155,12 @@ class IntentionListStep implements ListPopupStep Set wrappedNew = new THashSet(newDescriptors.size(), ACTION_TEXT_AND_CLASS_EQUALS); for (HighlightInfo.IntentionActionDescriptor descriptor : newDescriptors) { final IntentionAction action = descriptor.getAction(); - if (element != null && element != hostElement && ShowIntentionActionsHandler.availableFor(injectedFile, injectedEditor, action)) { + if (element != null && element != hostElement && (!callUpdate || ShowIntentionActionsHandler.availableFor(injectedFile, injectedEditor, action))) { IntentionActionWithTextCaching cachedAction = wrapAction(descriptor, element, injectedFile, injectedEditor); wrappedNew.add(cachedAction); changed |= cachedActions.add(cachedAction); } - else if (hostElement != null && ShowIntentionActionsHandler.availableFor(myFile, myEditor, action)) { + else if (hostElement != null && (!callUpdate || ShowIntentionActionsHandler.availableFor(myFile, myEditor, action))) { IntentionActionWithTextCaching cachedAction = wrapAction(descriptor, hostElement, myFile, myEditor); wrappedNew.add(cachedAction); changed |= cachedActions.add(cachedAction); From 35488c7a355190694e4a2faae962a3f62e09cf78 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Mon, 20 Jul 2015 15:21:18 +0300 Subject: [PATCH 034/106] cleanup --- .../openapi/projectRoots/ex/JavaSdkUtil.java | 28 +++++-------------- .../openapi/vfs/impl/jrt/JrtHandler.java | 9 ++---- .../problems/WolfTheProblemSolverImpl.java | 5 ++-- .../src/com/intellij/util/ReflectionUtil.java | 10 +++++++ 4 files changed, 21 insertions(+), 31 deletions(-) diff --git a/java/java-impl/src/com/intellij/openapi/projectRoots/ex/JavaSdkUtil.java b/java/java-impl/src/com/intellij/openapi/projectRoots/ex/JavaSdkUtil.java index 297a8282eca6..79208d963b24 100644 --- a/java/java-impl/src/com/intellij/openapi/projectRoots/ex/JavaSdkUtil.java +++ b/java/java-impl/src/com/intellij/openapi/projectRoots/ex/JavaSdkUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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,6 +18,7 @@ package com.intellij.openapi.projectRoots.ex; import com.intellij.rt.compiler.JavacRunner; import com.intellij.util.PathUtil; import com.intellij.util.PathsList; +import com.intellij.util.ReflectionUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -39,21 +40,11 @@ public class JavaSdkUtil { public static String getJunit4JarPath() { - try { - return PathUtil.getJarPathForClass(Class.forName("org.junit.Test")); - } - catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } + return PathUtil.getJarPathForClass(ReflectionUtil.forName("org.junit.Test")); } public static String getJunit3JarPath() { - try { - return PathUtil.getJarPathForClass(Class.forName("junit.runner.TestSuiteLoader")); //junit3 specific class - } - catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } + return PathUtil.getJarPathForClass(ReflectionUtil.forName("junit.runner.TestSuiteLoader")); //junit3 specific class } public static String getIdeaRtJarPath() { @@ -62,13 +53,8 @@ public class JavaSdkUtil { @NotNull public static List getJUnit4JarPaths() { - try { - return Arrays.asList(getJunit4JarPath(), - PathUtil.getJarPathForClass(Class.forName("org.hamcrest.Matcher")), - PathUtil.getJarPathForClass(Class.forName("org.hamcrest.Matchers"))); - } - catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } + return Arrays.asList(getJunit4JarPath(), + PathUtil.getJarPathForClass(ReflectionUtil.forName("org.hamcrest.Matcher")), + PathUtil.getJarPathForClass(ReflectionUtil.forName("org.hamcrest.Matchers"))); } } diff --git a/java/java-impl/src/com/intellij/openapi/vfs/impl/jrt/JrtHandler.java b/java/java-impl/src/com/intellij/openapi/vfs/impl/jrt/JrtHandler.java index 55a7379a127f..b41913da07d6 100644 --- a/java/java-impl/src/com/intellij/openapi/vfs/impl/jrt/JrtHandler.java +++ b/java/java-impl/src/com/intellij/openapi/vfs/impl/jrt/JrtHandler.java @@ -167,13 +167,8 @@ class JrtHandler extends ArchiveHandler { } private static Class cls(String name, boolean array) { - try { - if (array) name = "[L" + name + ";"; - return Class.forName(name); - } - catch (Exception e) { - throw new RuntimeException(e); - } + if (array) name = "[L" + name + ";"; + return ReflectionUtil.forName(name); } private static Method method(String name, Class... parameterTypes) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java index 73024b53862a..424876a172ad 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java @@ -55,7 +55,7 @@ import java.util.concurrent.atomic.AtomicReference; * @author cdr */ public class WolfTheProblemSolverImpl extends WolfTheProblemSolver { - private final Map myProblems = new THashMap(); + private final Map myProblems = new THashMap(); // guarded by myProblems private final Collection myCheckingQueue = new THashSet(10); private final Project myProject; @@ -322,8 +322,7 @@ public class WolfTheProblemSolverImpl extends WolfTheProblemSolver { if (!myProject.isOpen()) return false; synchronized (myProblems) { if (!myProblems.isEmpty()) { - Set problemFiles = myProblems.keySet(); - for (VirtualFile problemFile : problemFiles) { + for (VirtualFile problemFile : myProblems.keySet()) { if (problemFile.isValid() && condition.value(problemFile)) return true; } } diff --git a/platform/util/src/com/intellij/util/ReflectionUtil.java b/platform/util/src/com/intellij/util/ReflectionUtil.java index e3a61dc31a20..e83f4663860b 100644 --- a/platform/util/src/com/intellij/util/ReflectionUtil.java +++ b/platform/util/src/com/intellij/util/ReflectionUtil.java @@ -558,6 +558,16 @@ public class ReflectionUtil { return (field.getModifiers() & Modifier.FINAL) != 0; } + @NotNull + public static Class forName(@NotNull String fqn) { + try { + return Class.forName(fqn); + } + catch (Exception e) { + throw new RuntimeException(e); + } + } + private static class MySecurityManager extends SecurityManager { private static final MySecurityManager INSTANCE = new MySecurityManager(); From 6a2101c365115109f320996c085c271d7d94964e Mon Sep 17 00:00:00 2001 From: Daniil Ovchinnikov Date: Mon, 20 Jul 2015 15:50:12 +0300 Subject: [PATCH 035/106] [grails] annotations --- .../plugins/groovy/griffon/GriffonFramework.java | 4 +++- .../org/jetbrains/plugins/groovy/mvc/MvcFramework.java | 8 +++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/griffon/GriffonFramework.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/griffon/GriffonFramework.java index d1b84d5cffaf..e4479a1dae6a 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/griffon/GriffonFramework.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/griffon/GriffonFramework.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -80,6 +80,7 @@ public class GriffonFramework extends MvcFramework { return findAppRoot(module) != null && !isAuxModule(module) && getSdkRoot(module) != null; } + @NotNull @Override public String getApplicationDirectoryName() { return "griffon-app"; @@ -337,6 +338,7 @@ public class GriffonFramework extends MvcFramework { return params; } + @NotNull @Override public String getFrameworkName() { return "Griffon"; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java index f3f822557f1c..4f2730d60b4e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -103,6 +103,8 @@ public abstract class MvcFramework { return modules; } + @NonNls + @NotNull public abstract String getApplicationDirectoryName(); public void syncSdkAndLibrariesInPluginsModule(@NotNull Module module) { @@ -341,10 +343,14 @@ public abstract class MvcFramework { RunManagerEx.disableTasks(module.getProject(), configuration, CompileStepBeforeRun.ID, CompileStepBeforeRunNoErrorCheck.ID); } + @NonNls + @NotNull public abstract String getFrameworkName(); + public String getDisplayName() { return getFrameworkName(); } + public abstract Icon getIcon(); // 16*16 public abstract Icon getToolWindowIcon(); // 13*13 From cb9a1460616ba4078137aa8607aed13aafb20392 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Fri, 17 Jul 2015 16:35:31 +0200 Subject: [PATCH 036/106] =?UTF-8?q?cleanup=20=E2=80=94=20overrides,=20don'?= =?UTF-8?q?t=20implemet=20BaseComponent=20if=20not=20required?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../compiler/server/BuildManager.java | 18 ++-------- .../components/impl/ComponentManagerImpl.java | 2 +- .../openapi/actionSystem/ActionManager.java | 6 ++-- .../com/intellij/tools/BaseToolManager.java | 12 ++----- .../src/com/intellij/tools/ToolManager.java | 10 ------ .../openapi/command/CommandAdapter.java | 7 +++- .../actionSystem/impl/ActionManagerImpl.java | 9 ++--- .../impl/VirtualFilePointerManagerImpl.java | 16 +++------ .../vcs/changes/VcsDirtyScopeManagerImpl.java | 34 ++++++++++++++++++- .../vcs/impl/VcsGlobalMessageManager.java | 31 ++--------------- .../testing/VFSTestFrameworkListener.java | 19 ++--------- .../editorActions/XmlTagNameSynchronizer.java | 17 +++------- 12 files changed, 63 insertions(+), 118 deletions(-) diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java index 3d3a34d56d81..72391c13b2b4 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java @@ -43,7 +43,6 @@ import com.intellij.openapi.application.PathManager; import com.intellij.openapi.compiler.CompilationStatusListener; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompilerTopics; -import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.DocumentAdapter; @@ -109,8 +108,7 @@ import org.jetbrains.jps.incremental.Utils; import org.jetbrains.jps.model.serialization.JpsGlobalLoader; import javax.swing.*; -import javax.tools.JavaCompiler; -import javax.tools.ToolProvider; +import javax.tools.*; import java.awt.*; import java.io.File; import java.io.FileFilter; @@ -129,7 +127,7 @@ import static org.jetbrains.jps.api.CmdlineRemoteProto.Message.ControllerMessage * @author Eugene Zhuravlev * Date: 9/6/11 */ -public class BuildManager implements ApplicationComponent{ +public class BuildManager implements Disposable { public static final Key ALLOW_AUTOMAKE = Key.create("_allow_automake_when_process_is_active_"); private static final Key COMPILER_PROCESS_DEBUG_PORT = Key.create("_compiler_process_debug_port_"); private static final Key FORCE_MODEL_LOADING_PARAMETER = Key.create(BuildParametersKeys.FORCE_MODEL_LOADING); @@ -905,20 +903,10 @@ public class BuildManager implements ApplicationComponent{ } @Override - public void initComponent() { - } - - @Override - public void disposeComponent() { + public void dispose() { stopListening(); } - @NotNull - @Override - public String getComponentName() { - return "com.intellij.compiler.server.BuildManager"; - } - @NotNull public static Pair getBuildProcessRuntimeSdk(Project project) { Sdk projectJdk = null; 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 dfa793542a11..a90287473d31 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 @@ -372,7 +372,7 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements } @NotNull - public static String getComponentName(@NotNull final Object component) { + public static String getComponentName(@NotNull Object component) { if (component instanceof NamedComponent) { return ((NamedComponent)component).getComponentName(); } diff --git a/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/ActionManager.java b/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/ActionManager.java index bf83aee99f7d..3dbafb691364 100644 --- a/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/ActionManager.java +++ b/platform/editor-ui-api/src/com/intellij/openapi/actionSystem/ActionManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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,7 @@ package com.intellij.openapi.actionSystem; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.components.ApplicationComponent; +import com.intellij.openapi.components.NamedComponent; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.util.ActionCallback; import org.jetbrains.annotations.NonNls; @@ -35,7 +35,7 @@ import java.awt.event.InputEvent; * * @see AnAction */ -public abstract class ActionManager implements ApplicationComponent { +public abstract class ActionManager implements NamedComponent { /** * Fetches the instance of ActionManager implementation. diff --git a/platform/lang-impl/src/com/intellij/tools/BaseToolManager.java b/platform/lang-impl/src/com/intellij/tools/BaseToolManager.java index 26a373bfa83e..64e40622061d 100644 --- a/platform/lang-impl/src/com/intellij/tools/BaseToolManager.java +++ b/platform/lang-impl/src/com/intellij/tools/BaseToolManager.java @@ -16,7 +16,7 @@ package com.intellij.tools; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; -import com.intellij.openapi.components.ExportableApplicationComponent; +import com.intellij.openapi.components.ExportableComponent; import com.intellij.openapi.components.RoamingType; import com.intellij.openapi.options.SchemeProcessor; import com.intellij.openapi.options.SchemesManager; @@ -33,7 +33,7 @@ import java.util.Collections; import java.util.List; import java.util.Set; -public abstract class BaseToolManager implements ExportableApplicationComponent { +public abstract class BaseToolManager implements ExportableComponent { @NotNull private final ActionManagerEx myActionManager; private final SchemesManager, ToolsGroup> mySchemesManager; @@ -66,14 +66,6 @@ public abstract class BaseToolManager implements ExportableAppli return ToolsBundle.message("tools.settings"); } - @Override - public void disposeComponent() { - } - - @Override - public void initComponent() { - } - public List getTools() { List result = new SmartList(); for (ToolsGroup group : mySchemesManager.getAllSchemes()) { diff --git a/platform/lang-impl/src/com/intellij/tools/ToolManager.java b/platform/lang-impl/src/com/intellij/tools/ToolManager.java index dfabbfe68770..345dd7a383b1 100644 --- a/platform/lang-impl/src/com/intellij/tools/ToolManager.java +++ b/platform/lang-impl/src/com/intellij/tools/ToolManager.java @@ -19,11 +19,7 @@ import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.options.SchemeProcessor; import com.intellij.openapi.options.SchemesManagerFactory; -import org.jetbrains.annotations.NotNull; -/** - * @author traff - */ public class ToolManager extends BaseToolManager { public ToolManager(ActionManagerEx actionManagerEx, SchemesManagerFactory factory) { @@ -59,10 +55,4 @@ public class ToolManager extends BaseToolManager { public static ToolManager getInstance() { return ApplicationManager.getApplication().getComponent(ToolManager.class); } - - @Override - @NotNull - public String getComponentName() { - return "ToolManager"; - } } diff --git a/platform/platform-api/src/com/intellij/openapi/command/CommandAdapter.java b/platform/platform-api/src/com/intellij/openapi/command/CommandAdapter.java index 5b60c67195de..6a6e52e97216 100644 --- a/platform/platform-api/src/com/intellij/openapi/command/CommandAdapter.java +++ b/platform/platform-api/src/com/intellij/openapi/command/CommandAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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,18 +16,23 @@ package com.intellij.openapi.command; public abstract class CommandAdapter implements CommandListener{ + @Override public void commandStarted(CommandEvent event) { } + @Override public void beforeCommandFinished(CommandEvent event) { } + @Override public void commandFinished(CommandEvent event) { } + @Override public void undoTransparentActionStarted() { } + @Override public void undoTransparentActionFinished() { } } \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java index a64a2eff492d..d00f8d5eaa71 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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,6 @@ import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.application.*; import com.intellij.openapi.application.ex.ApplicationManagerEx; -import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.keymap.Keymap; @@ -73,7 +72,7 @@ import java.util.*; import java.util.List; import java.util.concurrent.Future; -public final class ActionManagerImpl extends ActionManagerEx implements ApplicationComponent { +public final class ActionManagerImpl extends ActionManagerEx implements Disposable { @NonNls public static final String ACTION_ELEMENT_NAME = "action"; @NonNls public static final String GROUP_ELEMENT_NAME = "group"; @NonNls public static final String ACTIONS_ELEMENT_NAME = "actions"; @@ -404,11 +403,9 @@ public final class ActionManagerImpl extends ActionManagerEx implements Applicat return contextComponent != null ? dataManager.getDataContext(contextComponent) : dataManager.getDataContext(); } - @Override - public void initComponent() {} @Override - public void disposeComponent() { + public void dispose() { if (myTimer != null) { myTimer.stop(); myTimer = null; 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 76bd6f170c71..3418b4d6ee12 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 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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.openapi.vfs.impl; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.components.ApplicationComponent; +import com.intellij.openapi.components.NamedComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; @@ -46,7 +46,7 @@ import org.jetbrains.annotations.TestOnly; import java.util.*; import java.util.concurrent.ConcurrentMap; -public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager implements ApplicationComponent, ModificationTracker, BulkFileListener { +public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager implements NamedComponent, ModificationTracker, BulkFileListener, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl"); private final TempFileSystem TEMP_FILE_SYSTEM; private final LocalFileSystem LOCAL_FILE_SYSTEM; @@ -84,15 +84,6 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp JAR_FILE_SYSTEM = jarFileSystem; } - @Override - public void initComponent() { - } - - @Override - public void disposeComponent() { - assertAllPointersDisposed(); - } - @NotNull @Override public String getComponentName() { @@ -347,6 +338,7 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp @Override public void dispose() { + assertAllPointersDisposed(); } @Override diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsDirtyScopeManagerImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsDirtyScopeManagerImpl.java index 9b66d5016100..4c02c6cd5c6b 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsDirtyScopeManagerImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsDirtyScopeManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -66,6 +66,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr ((ChangeListManagerImpl) myChangeListManager).setDirtyScopeManager(this); } + @Override public void projectOpened() { if (ApplicationManager.getApplication().isUnitTestMode()) { myLife.born(); @@ -76,9 +77,11 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } else { StartupManager.getInstance(myProject).registerPostStartupActivity(new DumbAwareRunnable() { + @Override public void run() { myLife.born(); ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { + @Override public void run() { markEverythingDirty(); } @@ -95,6 +98,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr public void reanimate() { final Ref wasNotEmptyRef = new Ref(); myLife.releaseMe(new Runnable() { + @Override public void run() { wasNotEmptyRef.set(! myDirtBuilder.isEmpty()); } @@ -104,6 +108,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } } + @Override public void markEverythingDirty() { if ((! myProject.isOpen()) || myProject.isDisposed() || myVcsManager.getAllActiveVcss().length == 0) return; @@ -112,6 +117,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } final LifeDrop lifeDrop = myLife.doIfAlive(new Runnable() { + @Override public void run() { myDirtBuilder.everythingDirty(); } @@ -122,25 +128,30 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } } + @Override public void projectClosed() { killSelf(); } + @Override @NotNull @NonNls public String getComponentName() { return "VcsDirtyScopeManager"; } + @Override public void initComponent() {} private void killSelf() { myLife.kill(new Runnable() { + @Override public void run() { myDirtBuilder.reset(); } }); } + @Override public void disposeComponent() { killSelf(); } @@ -161,6 +172,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } } + @Override public void filePathsDirty(@Nullable final Collection filesDirty, @Nullable final Collection dirsRecursivelyDirty) { try { final ArrayList filesConverted = filesDirty == null ? null : new ArrayList(filesDirty.size()); @@ -177,6 +189,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } takeDirt(new Consumer() { + @Override public void consume(final DirtBuilder dirt) { if (filesConverted != null) { for (FilePathUnderVcs root : filesConverted) { @@ -197,6 +210,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr private void takeDirt(final Consumer filler) { final Ref wasNotEmptyRef = new Ref(); final Runnable runnable = new Runnable() { + @Override public void run() { filler.consume(myDirtBuilder); wasNotEmptyRef.set(!myDirtBuilder.isEmpty()); @@ -213,6 +227,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr if (from != null) { for (final VirtualFile vf : from) { ApplicationManager.getApplication().runReadAction(new Runnable() { + @Override public void run() { final AbstractVcs vcs = myGuess.getVcsForDirty(vf); if (vcs != null) { @@ -224,6 +239,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } } + @Override public void filesDirty(@Nullable final Collection filesDirty, @Nullable final Collection dirsRecursivelyDirty) { try { final ArrayList filesConverted = filesDirty == null ? null : new ArrayList(filesDirty.size()); @@ -239,6 +255,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } takeDirt(new Consumer() { + @Override public void consume(final DirtBuilder dirt) { if (filesConverted != null) { for (VcsRoot root : filesConverted) { @@ -256,6 +273,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } } + @Override public void fileDirty(@NotNull final VirtualFile file) { try { final AbstractVcs vcs = myGuess.getVcsForDirty(file); @@ -265,6 +283,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } final VcsRoot root = new VcsRoot(vcs, file); takeDirt(new Consumer() { + @Override public void consume(DirtBuilder dirtBuilder) { dirtBuilder.addDirtyFile(root); } @@ -273,6 +292,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } } + @Override public void fileDirty(@NotNull final FilePath file) { try { final AbstractVcs vcs = myGuess.getVcsForDirty(file); @@ -282,6 +302,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } final FilePathUnderVcs root = new FilePathUnderVcs(file, vcs); takeDirt(new Consumer() { + @Override public void consume(DirtBuilder dirtBuilder) { dirtBuilder.addDirtyFile(root); } @@ -290,10 +311,12 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } } + @Override public void dirDirtyRecursively(final VirtualFile dir, final boolean scheduleUpdate) { dirDirtyRecursively(dir); } + @Override public void dirDirtyRecursively(final VirtualFile dir) { try { final AbstractVcs vcs = myGuess.getVcsForDirty(dir); @@ -303,6 +326,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } final VcsRoot root = new VcsRoot(vcs, dir); takeDirt(new Consumer() { + @Override public void consume(DirtBuilder dirtBuilder) { dirtBuilder.addDirtyDirRecursively(root); } @@ -311,6 +335,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } } + @Override public void dirDirtyRecursively(final FilePath path) { try { final AbstractVcs vcs = myGuess.getVcsForDirty(path); @@ -320,6 +345,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } final FilePathUnderVcs root = new FilePathUnderVcs(path, vcs); takeDirt(new Consumer() { + @Override public void consume(DirtBuilder dirtBuilder) { dirtBuilder.addDirtyDirRecursively(root); } @@ -371,9 +397,11 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr } } + @Override @Nullable public VcsInvalidated retrieveScopes() { final LifeDrop lifeDrop = myLife.doIfAlive(new Runnable() { + @Override public void run() { myProgressHolder.takeNext(new DirtBuilder(myDirtBuilder)); myDirtBuilder.reset(); @@ -384,6 +412,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr final VcsInvalidated invalidated = myProgressHolder.calculateInvalidated(); myLife.doIfAlive(new Runnable() { + @Override public void run() { myProgressHolder.takeInvalidated(invalidated); } @@ -393,8 +422,10 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr return null; } + @Override public void changesProcessed() { myLife.doIfAlive(new Runnable() { + @Override public void run() { myProgressHolder.processed(); } @@ -409,6 +440,7 @@ public class VcsDirtyScopeManagerImpl extends VcsDirtyScopeManager implements Pr final Ref currentHolderRef = new Ref(); myLife.doIfAlive(new Runnable() { + @Override public void run() { inProgressHolderRef.set(myProgressHolder.copy()); currentHolderRef.set(new MyProgressHolder(new DirtBuilder(myDirtBuilder), null)); diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsGlobalMessageManager.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsGlobalMessageManager.java index b16a93e08387..815831143bac 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsGlobalMessageManager.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsGlobalMessageManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -26,7 +26,6 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.util.ui.UIUtil; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -44,7 +43,7 @@ import java.awt.*; @Storage(file = StoragePathMacros.PROJECT_FILE), @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/vcs.xml", scheme = StorageScheme.DIRECTORY_BASED) }) -public class VcsGlobalMessageManager implements ProjectComponent, PersistentStateComponent { +public class VcsGlobalMessageManager implements PersistentStateComponent { private VcsGlobalMessage myState; public static VcsGlobalMessageManager getInstance(final Project project) { @@ -62,26 +61,6 @@ public class VcsGlobalMessageManager implements ProjectComponent, PersistentStat myState = state == null ? new VcsGlobalMessage() : state; } - @Override - public void projectOpened() { - - } - - @Override - public void projectClosed() { - - } - - @Override - public void initComponent() { - - } - - @Override - public void disposeComponent() { - - } - @Nullable public JComponent getMessageBanner() { if (ApplicationManagerEx.getApplicationEx().isInternal()) { @@ -128,10 +107,4 @@ public class VcsGlobalMessageManager implements ProjectComponent, PersistentStat return null; } - - @NotNull - @Override - public String getComponentName() { - return "VcsGlobalMessageManager"; - } } diff --git a/python/src/com/jetbrains/python/testing/VFSTestFrameworkListener.java b/python/src/com/jetbrains/python/testing/VFSTestFrameworkListener.java index c5b4992462bd..0d4961489c08 100644 --- a/python/src/com/jetbrains/python/testing/VFSTestFrameworkListener.java +++ b/python/src/com/jetbrains/python/testing/VFSTestFrameworkListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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,6 @@ package com.jetbrains.python.testing; import com.intellij.execution.ExecutionException; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.projectRoots.Sdk; @@ -44,7 +43,7 @@ import java.util.List; /** * User: catherine */ -public class VFSTestFrameworkListener implements ApplicationComponent { +public class VFSTestFrameworkListener { private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.testing.VFSTestFrameworkListener"); private static final MergingUpdateQueue myQueue = new MergingUpdateQueue("TestFrameworkChecker", 5000, true, null); private PyTestFrameworkService myService; @@ -108,20 +107,6 @@ public class VFSTestFrameworkListener implements ApplicationComponent { }); } - @Override - public void initComponent() { - } - - @Override - public void disposeComponent() { - } - - @NotNull - @Override - public String getComponentName() { - return "VFSTestFrameworkListener"; - } - /** * @return null if we can't be sure */ diff --git a/xml/impl/src/com/intellij/codeInsight/editorActions/XmlTagNameSynchronizer.java b/xml/impl/src/com/intellij/codeInsight/editorActions/XmlTagNameSynchronizer.java index a2b77bc611fc..c22933500e0e 100644 --- a/xml/impl/src/com/intellij/codeInsight/editorActions/XmlTagNameSynchronizer.java +++ b/xml/impl/src/com/intellij/codeInsight/editorActions/XmlTagNameSynchronizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -31,7 +31,7 @@ import com.intellij.openapi.command.CommandAdapter; import com.intellij.openapi.command.CommandEvent; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.undo.UndoManager; -import com.intellij.openapi.components.ApplicationComponent; +import com.intellij.openapi.components.NamedComponent; import com.intellij.openapi.diagnostic.Attachment; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; @@ -66,7 +66,7 @@ import java.util.Set; /** * @author Dennis.Ushakov */ -public class XmlTagNameSynchronizer extends CommandAdapter implements ApplicationComponent { +public class XmlTagNameSynchronizer extends CommandAdapter implements NamedComponent { private static final Logger LOG = Logger.getInstance(XmlTagNameSynchronizer.class); private static final Set SUPPORTED_LANGUAGES = ContainerUtil.set(HTMLLanguage.INSTANCE.getID(), XMLLanguage.INSTANCE.getID(), @@ -128,16 +128,6 @@ public class XmlTagNameSynchronizer extends CommandAdapter implements Applicatio return "XmlTagNameSynchronizer"; } - @Override - public void initComponent() { - - } - - @Override - public void disposeComponent() { - - } - @Nullable public TagNameSynchronizer findSynchronizer(final Document document) { if (!WebEditorOptions.getInstance().isSyncTagEditing() || document == null) return null; @@ -308,6 +298,7 @@ public class XmlTagNameSynchronizer extends CommandAdapter implements Applicatio final Document document = myEditor.getDocument(); final Runnable apply = new Runnable() { + @Override public void run() { for (Couple couple : myMarkers) { final RangeMarker leader = couple.first; From 32e61096e1d432268a78839ebcbe6d28e6cb6d24 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Fri, 17 Jul 2015 18:05:49 +0200 Subject: [PATCH 037/106] =?UTF-8?q?save=20memory=20=E2=80=94=20get=20rid?= =?UTF-8?q?=20of=20myInterfaceToClassMap?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../roots/ui/configuration/ModuleEditor.java | 7 ++- .../ex/InspectionToolRegistrar.java | 3 +- .../src/com/intellij/mock/MockProject.java | 8 ++- .../components/impl/ComponentManagerImpl.java | 55 ++++++------------- .../impl/AllFileTemplatesConfigurable.java | 9 ++- .../openapi/module/impl/ModuleImpl.java | 14 ++--- .../intellij/diagnostic/DialogAppender.java | 3 +- .../ide/actions/ExportSettingsAction.java | 4 +- .../intellij/openapi/components/service.kt | 6 +- .../ex/ConfigurableExtensionPointUtil.java | 20 +++---- .../options/ex/ConfigurablesGroupBase.java | 7 ++- .../openapi/project/impl/ProjectImpl.java | 14 ++--- .../util/pico/DefaultPicoContainer.java | 7 ++- .../ui/ChangesBrowserChangeListNode.java | 10 ++-- 14 files changed, 79 insertions(+), 88 deletions(-) diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java index 31cad7748450..e06d547ecc83 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModuleEditor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -19,6 +19,7 @@ import com.intellij.facet.impl.ProjectFacetsConfigurator; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.LangDataKeys; +import com.intellij.openapi.components.ComponentsPackage; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.Module; @@ -202,7 +203,7 @@ public abstract class ModuleEditor implements Place.Navigator, Disposable { } } - for (final Configurable moduleConfigurable : myModule.getComponents(Configurable.class)) { + for (Configurable moduleConfigurable : ComponentsPackage.getComponents(myModule, Configurable.class)) { myEditors.add(new ModuleConfigurableWrapper(moduleConfigurable)); } for(ModuleConfigurableEP extension : myModule.getExtensions(MODULE_CONFIGURABLES)) { @@ -214,7 +215,7 @@ public abstract class ModuleEditor implements Place.Navigator, Disposable { private static ModuleConfigurationEditorProvider[] collectProviders(final Module module) { List result = new ArrayList(); - ContainerUtil.addAll(result, module.getComponents(ModuleConfigurationEditorProvider.class)); + result.addAll(ComponentsPackage.getComponents(module, ModuleConfigurationEditorProvider.class)); ContainerUtil.addAll(result, Extensions.getExtensions(ModuleConfigurationEditorProvider.EP_NAME, module)); return result.toArray(new ModuleConfigurationEditorProvider[result.size()]); } diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionToolRegistrar.java b/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionToolRegistrar.java index 1bffd39a0c24..59c71ad51ab2 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionToolRegistrar.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionToolRegistrar.java @@ -46,7 +46,8 @@ public class InspectionToolRegistrar { if (!myInspectionComponentsLoaded) { myInspectionComponentsLoaded = true; Set providers = new THashSet(); - ContainerUtil.addAll(providers, ApplicationManager.getApplication().getComponents(InspectionToolProvider.class)); + //noinspection unchecked + providers.addAll((Collection)ApplicationManager.getApplication().getPicoContainer().getComponentInstancesOfType(InspectionToolProvider.class)); ContainerUtil.addAll(providers, Extensions.getExtensions(InspectionToolProvider.EXTENSION_POINT_NAME)); List> factories = new ArrayList>(); registerTools(providers, factories); diff --git a/platform/core-impl/src/com/intellij/mock/MockProject.java b/platform/core-impl/src/com/intellij/mock/MockProject.java index 72870cc78365..49a8321ff2ec 100644 --- a/platform/core-impl/src/com/intellij/mock/MockProject.java +++ b/platform/core-impl/src/com/intellij/mock/MockProject.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2015 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,8 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.picocontainer.PicoContainer; +import java.util.List; + /** * @author yole */ @@ -137,8 +139,8 @@ public class MockProject extends MockComponentManager implements Project { } public void projectOpened() { - final ProjectComponent[] components = getComponents(ProjectComponent.class); - for (ProjectComponent component : components) { + //noinspection unchecked + for (ProjectComponent component : ((List)getPicoContainer().getComponentInstancesOfType(ProjectComponent.class))) { try { component.projectOpened(); } 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 a90287473d31..09260ec8e457 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 @@ -28,7 +28,7 @@ import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.ReflectionUtil; +import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusFactory; @@ -40,7 +40,6 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.picocontainer.*; -import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -157,12 +156,12 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements @Nullable private T getComponentFromContainer(@NotNull Class componentInterface) { T component = (T)myInitializedComponents.get(componentInterface); - if (component != null) { + if (component != null || myDisposed) { return component; } synchronized (this) { - if (myComponentsRegistry == null || !myComponentsRegistry.containsInterface(componentInterface)) { + if (myComponentsRegistry == null) { return null; } @@ -235,13 +234,21 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements @Override public synchronized boolean hasComponent(@NotNull Class interfaceClass) { - return myComponentsRegistry != null && myComponentsRegistry.containsInterface(interfaceClass); + return myComponentsRegistry != null && getPicoContainer().getComponentAdapter(interfaceClass.getName()) != null; } @Override @NotNull - public synchronized T[] getComponents(@NotNull Class baseClass) { - return myComponentsRegistry.getComponentsByType(baseClass); + public T[] getComponents(@NotNull Class baseClass) { + List list = getPicoContainer().getComponentInstancesOfType(baseClass); + //noinspection unchecked + return (T[])ArrayUtil.toObjectArray(list, baseClass); + } + + @NotNull + protected final List getComponentInstancesOfType(@NotNull Class baseClass) { + //noinspection unchecked + return getPicoContainer().getComponentInstancesOfType(baseClass); } @Override @@ -385,7 +392,6 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements private class ComponentsRegistry { private final Map myInterfaceToLockMap = new THashMap(); - private final Map myInterfaceToClassMap = new THashMap(); private final List myComponentInterfaces; // keeps order of component's registration private final Map myNameToComponent = new THashMap(); private final int myComponentConfigsSize; @@ -395,38 +401,31 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements public ComponentsRegistry(@NotNull List componentConfigs) { myComponentInterfaces = new ArrayList(componentConfigs.size()); for (ComponentConfig config : componentConfigs) { - loadClasses(config); + registerComponents(config); } myComponentConfigsSize = componentConfigs.size(); } - private void loadClasses(@NotNull ComponentConfig config) { + private void registerComponents(@NotNull ComponentConfig config) { ClassLoader loader = config.getClassLoader(); try { final Class interfaceClass = Class.forName(config.getInterfaceClass(), true, loader); final Class implementationClass = Comparing.equal(config.getInterfaceClass(), config.getImplementationClass()) ? interfaceClass : StringUtil.isEmpty(config.getImplementationClass()) ? null : Class.forName(config.getImplementationClass(), true, loader); - boolean overrides = config.options != null && Boolean.parseBoolean(config.options.get("overrides")); MutablePicoContainer picoContainer = getPicoContainer(); - if (overrides) { + if (config.options != null && Boolean.parseBoolean(config.options.get("overrides"))) { ComponentAdapter oldAdapter = picoContainer.getComponentAdapterOfType(interfaceClass); if (oldAdapter == null) { throw new RuntimeException(config + " does not override anything"); } picoContainer.unregisterComponent(oldAdapter.getComponentKey()); - myInterfaceToClassMap.remove(interfaceClass); myComponentClassToConfig.remove(oldAdapter.getComponentImplementation()); myComponentInterfaces.remove(interfaceClass); } // implementationClass == null means we want to unregister this component if (implementationClass != null) { - if (myInterfaceToClassMap.get(interfaceClass) != null) { - throw new RuntimeException("Component already registered: " + interfaceClass.getName()); - } - picoContainer.registerComponent(new ComponentConfigComponentAdapter(config, implementationClass)); - myInterfaceToClassMap.put(interfaceClass, implementationClass); myComponentClassToConfig.put(implementationClass, config); myComponentInterfaces.add(interfaceClass); } @@ -444,10 +443,6 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements return lock; } - private boolean containsInterface(final Class interfaceClass) { - return myInterfaceToClassMap.containsKey(interfaceClass); - } - private double getPercentageOfComponentsLoaded() { return ((double)myImplementations.size()) / myComponentConfigsSize; } @@ -481,22 +476,6 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements return myNameToComponent.get(name); } - @SuppressWarnings("unchecked") - private T[] getComponentsByType(final Class baseClass) { - List array = new ArrayList(); - - //noinspection ForLoopReplaceableByForEach - for (int i = 0; i < myComponentInterfaces.size(); i++) { - Class interfaceClass = myComponentInterfaces.get(i); - final Class implClass = myInterfaceToClassMap.get(interfaceClass); - if (ReflectionUtil.isAssignable(baseClass, implClass)) { - array.add((T)getComponent(interfaceClass)); - } - } - - return array.toArray((T[])Array.newInstance(baseClass, array.size())); - } - public ComponentConfig getConfig(final Class componentImplementation) { return myComponentClassToConfig.get(componentImplementation); } diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/AllFileTemplatesConfigurable.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/AllFileTemplatesConfigurable.java index cf2c8e98332e..bc3638498dbf 100644 --- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/AllFileTemplatesConfigurable.java +++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/AllFileTemplatesConfigurable.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -23,6 +23,7 @@ import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.components.ComponentsPackage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.options.Configurable; @@ -35,7 +36,9 @@ import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; -import com.intellij.ui.*; +import com.intellij.ui.IdeBorderFactory; +import com.intellij.ui.ScrollPaneFactory; +import com.intellij.ui.TabbedPaneWrapper; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.PlatformIcons; @@ -216,7 +219,7 @@ public class AllFileTemplatesConfigurable implements SearchableConfigurable, Con final List allTabs = new ArrayList(Arrays.asList(myTemplatesList, myIncludesList, myCodeTemplatesList)); final Set factories = new THashSet(); - ContainerUtil.addAll(factories, ApplicationManager.getApplication().getComponents(FileTemplateGroupDescriptorFactory.class)); + factories.addAll(ComponentsPackage.getComponents(ApplicationManager.getApplication(), FileTemplateGroupDescriptorFactory.class)); ContainerUtil.addAll(factories, Extensions.getExtensions(FileTemplateGroupDescriptorFactory.EXTENSION_POINT_NAME)); if (!factories.isEmpty()) { diff --git a/platform/lang-impl/src/com/intellij/openapi/module/impl/ModuleImpl.java b/platform/lang-impl/src/com/intellij/openapi/module/impl/ModuleImpl.java index 7def1647dd49..df6ae6482d0c 100644 --- a/platform/lang-impl/src/com/intellij/openapi/module/impl/ModuleImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/module/impl/ModuleImpl.java @@ -181,7 +181,7 @@ public class ModuleImpl extends PlatformComponentManagerImpl implements ModuleEx @Override public void projectOpened() { - for (ModuleComponent component : getComponents(ModuleComponent.class)) { + for (ModuleComponent component : getComponentInstancesOfType(ModuleComponent.class)) { try { component.projectOpened(); } @@ -193,14 +193,12 @@ public class ModuleImpl extends PlatformComponentManagerImpl implements ModuleEx @Override public void projectClosed() { - List components = new ArrayList(Arrays.asList(getComponents(ModuleComponent.class))); - Collections.reverse(components); - - for (ModuleComponent component : components) { + List components = getComponentInstancesOfType(ModuleComponent.class); + for (int i = components.size() - 1; i >= 0; i--) { try { - component.projectClosed(); + components.get(i).projectClosed(); } - catch (Exception e) { + catch (Throwable e) { LOG.error(e); } } @@ -226,7 +224,7 @@ public class ModuleImpl extends PlatformComponentManagerImpl implements ModuleEx @Override public void moduleAdded() { isModuleAdded = true; - for (ModuleComponent component : getComponents(ModuleComponent.class)) { + for (ModuleComponent component : getComponentInstancesOfType(ModuleComponent.class)) { component.moduleAdded(); } } diff --git a/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java b/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java index 165613cb534f..fa25a6763d26 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/DialogAppender.java @@ -19,6 +19,7 @@ import com.intellij.idea.IdeaApplication; import com.intellij.idea.Main; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.components.ComponentsPackage; import com.intellij.openapi.diagnostic.ErrorLogger; import com.intellij.openapi.diagnostic.ExceptionWithAttachments; import com.intellij.openapi.diagnostic.IdeaLoggingEvent; @@ -64,7 +65,7 @@ public class DialogAppender extends AppenderSkeleton { Application application = ApplicationManager.getApplication(); if (application != null) { if (application.isHeadlessEnvironment() || application.isDisposed()) return; - ContainerUtil.addAll(loggers, application.getComponents(ErrorLogger.class)); + ContainerUtil.addAll(loggers, ComponentsPackage.getComponents(application, ErrorLogger.class)); } appendToLoggers(event, loggers.toArray(new ErrorLogger[loggers.size()])); diff --git a/platform/platform-impl/src/com/intellij/ide/actions/ExportSettingsAction.java b/platform/platform-impl/src/com/intellij/ide/actions/ExportSettingsAction.java index 36fe21d229ca..376a03fb76b8 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/ExportSettingsAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/ExportSettingsAction.java @@ -161,10 +161,10 @@ public class ExportSettingsAction extends AnAction implements DumbAware { @NotNull public static MultiMap getExportableComponentsMap(final boolean onlyExisting, final boolean computePresentableNames) { @SuppressWarnings("deprecation") - ExportableApplicationComponent[] components1 = ApplicationManager.getApplication().getComponents(ExportableApplicationComponent.class); + List components1 = ComponentsPackage.getComponents(ApplicationManager.getApplication(), ExportableApplicationComponent.class); List components2 = ServiceBean.loadServicesFromBeans(ExportableComponent.EXTENSION_POINT, ExportableComponent.class); final MultiMap result = MultiMap.createLinkedSet(); - for (ExportableComponent component : ContainerUtil.concat(Arrays.asList(components1), components2)) { + for (ExportableComponent component : ContainerUtil.concat(components1, components2)) { for (File exportFile : component.getExportFiles()) { result.putValue(exportFile, component); } diff --git a/platform/platform-impl/src/com/intellij/openapi/components/service.kt b/platform/platform-impl/src/com/intellij/openapi/components/service.kt index ff796007646e..43a79eb7a82f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/service.kt +++ b/platform/platform-impl/src/com/intellij/openapi/components/service.kt @@ -23,4 +23,8 @@ public inline fun service(): T? = ServiceManager.getService(jav public inline fun Project.service(): T? = ServiceManager.getService(this, javaClass()) public val ComponentManager.stateStore: IComponentStore - get() = getPicoContainer().getComponentInstance(javaClass()) as IComponentStore \ No newline at end of file + get() = getPicoContainer().getComponentInstance(javaClass()) as IComponentStore + + +@suppress("UNCHECKED_CAST") +public fun ComponentManager.getComponents(baseClass: Class): List = getPicoContainer().getComponentInstancesOfType(baseClass) as List diff --git a/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurableExtensionPointUtil.java b/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurableExtensionPointUtil.java index af33fdb5d9fa..059f3394f649 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurableExtensionPointUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurableExtensionPointUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2015 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,6 +17,7 @@ package com.intellij.openapi.options.ex; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.components.ComponentsPackage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.*; import com.intellij.openapi.project.Project; @@ -41,7 +42,7 @@ public class ConfigurableExtensionPointUtil { public static List buildConfigurablesList(final ConfigurableEP[] extensions, - final Configurable[] components, + final List components, @Nullable ConfigurableFilter filter) { final List result = new ArrayList(); for (Configurable component : components) { @@ -312,7 +313,9 @@ public class ConfigurableExtensionPointUtil { Application application = ApplicationManager.getApplication(); if (application != null) { if (loadComponents) { - addValid(list, application.getComponents(Configurable.class), null); + for (Configurable configurable : ComponentsPackage.getComponents(application, Configurable.class)) { + addValid(list, configurable, project); + } } for (ConfigurableEP extension : application.getExtensions(Configurable.APPLICATION_CONFIGURABLE)) { addValid(list, ConfigurableWrapper.wrapConfigurable(extension), null); @@ -320,8 +323,9 @@ public class ConfigurableExtensionPointUtil { } } if (project != null && !project.isDisposed()) { - if (loadComponents) { - addValid(list, project.getComponents(Configurable.class), project); + //noinspection unchecked + for (Configurable configurable : ComponentsPackage.getComponents(project, Configurable.class)) { + addValid(list, configurable, project); } for (ConfigurableEP extension : project.getExtensions(Configurable.PROJECT_CONFIGURABLE)) { addValid(list, ConfigurableWrapper.wrapConfigurable(extension), project); @@ -336,12 +340,6 @@ public class ConfigurableExtensionPointUtil { } } - private static void addValid(List list, Configurable[] configurables, Project project) { - for (Configurable configurable : configurables) { - addValid(list, configurable, project); - } - } - /** * @param configurable settings component to validate * @param project current project, default template project or {@code null} for IDE settings diff --git a/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurablesGroupBase.java b/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurablesGroupBase.java index 3acf9e89e79a..988fee36bb6e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurablesGroupBase.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurablesGroupBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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,12 +16,14 @@ package com.intellij.openapi.options.ex; import com.intellij.openapi.components.ComponentManager; +import com.intellij.openapi.components.ComponentsPackage; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurableEP; import com.intellij.openapi.options.ConfigurableGroup; import org.jetbrains.annotations.Nullable; +import java.util.Collections; import java.util.List; /** @@ -47,8 +49,7 @@ public abstract class ConfigurablesGroupBase implements ConfigurableGroup { return new Configurable[0]; } final ConfigurableEP[] extensions = myComponentManager.getExtensions(myConfigurablesExtensionPoint); - Configurable[] components = myLoadComponents ? myComponentManager.getComponents(Configurable.class) : new Configurable[0]; - + List components = myLoadComponents ? ComponentsPackage.getComponents(myComponentManager, Configurable.class) : Collections.emptyList(); List result = ConfigurableExtensionPointUtil.buildConfigurablesList(extensions, components, getConfigurableFilter()); myChildren = result.toArray(new Configurable[result.size()]); } diff --git a/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectImpl.java b/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectImpl.java index cbc2f80e391a..f441b5cfcaf0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectImpl.java @@ -61,7 +61,9 @@ import org.picocontainer.*; import javax.swing.*; import java.io.File; -import java.util.*; +import java.util.Iterator; +import java.util.List; +import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; public class ProjectImpl extends PlatformComponentManagerImpl implements ProjectEx { @@ -385,8 +387,7 @@ public class ProjectImpl extends PlatformComponentManagerImpl implements Project } private void projectOpened() { - final ProjectComponent[] components = getComponents(ProjectComponent.class); - for (ProjectComponent component : components) { + for (ProjectComponent component : getComponentInstancesOfType(ProjectComponent.class)) { try { component.projectOpened(); } @@ -397,11 +398,10 @@ public class ProjectImpl extends PlatformComponentManagerImpl implements Project } private void projectClosed() { - List components = new ArrayList(Arrays.asList(getComponents(ProjectComponent.class))); - Collections.reverse(components); - for (ProjectComponent component : components) { + List components = getComponentInstancesOfType(ProjectComponent.class); + for (int i = components.size() - 1; i >= 0; i--) { try { - component.projectClosed(); + components.get(i).projectClosed(); } catch (Throwable e) { LOG.error(e); diff --git a/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java b/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java index 23fe1d7362c9..f569c2060090 100644 --- a/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java +++ b/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java @@ -153,7 +153,8 @@ public class DefaultPicoContainer implements AreaPicoContainer, Serializable { if (nonAssignableComponentAdapters.compareAndSet(oldList, newList)) { break; } - } while (true); + } + while (true); } componentAdapters.add(componentAdapter); @@ -188,13 +189,13 @@ public class DefaultPicoContainer implements AreaPicoContainer, Serializable { } @Override - public List getComponentInstancesOfType(Class componentType) { + public List getComponentInstancesOfType(@Nullable Class componentType) { if (componentType == null) { return Collections.emptyList(); } List result = new ArrayList(); - for (final ComponentAdapter componentAdapter : getComponentAdapters()) { + for (ComponentAdapter componentAdapter : getComponentAdapters()) { if (ReflectionUtil.isAssignable(componentType, componentAdapter.getComponentImplementation())) { // may be null in the case of the "implicit" adapter representing "this". ContainerUtil.addIfNotNull(result, getInstance(componentAdapter)); diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesBrowserChangeListNode.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesBrowserChangeListNode.java index e6d1de6e7678..1a0abe87b9b0 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesBrowserChangeListNode.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesBrowserChangeListNode.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -29,7 +29,7 @@ import java.util.List; * @author yole */ public class ChangesBrowserChangeListNode extends ChangesBrowserNode { - private final ChangeListDecorator[] myDecorators; + private final List myDecorators; private final ChangeListManagerEx myClManager; private final ChangeListRemoteState myChangeListRemoteState; @@ -37,7 +37,9 @@ public class ChangesBrowserChangeListNode extends ChangesBrowserNode super(userObject); myChangeListRemoteState = changeListRemoteState; myClManager = (ChangeListManagerEx) ChangeListManager.getInstance(project); - myDecorators = project.getComponents(ChangeListDecorator.class); + + //noinspection unchecked + myDecorators = project.getPicoContainer().getComponentInstancesOfType(ChangeListDecorator.class); } @Override @@ -47,7 +49,7 @@ public class ChangesBrowserChangeListNode extends ChangesBrowserNode renderer.appendTextWithIssueLinks(list.getName(), list.isDefault() ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES); appendCount(renderer); - for(ChangeListDecorator decorator: myDecorators) { + for (ChangeListDecorator decorator: myDecorators) { decorator.decorateChangeList(list, renderer, selected, expanded, hasFocus); } final String freezed = myClManager.isFreezed(); From 86729dfeaf81bc8b1f92a9471e780df4f40a2a17 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Fri, 17 Jul 2015 18:09:36 +0200 Subject: [PATCH 038/106] revert, dispose logic is tricky, should be investigated later --- .../vfs/impl/VirtualFilePointerManagerImpl.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) 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 3418b4d6ee12..dd37dcd9af42 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 @@ -17,7 +17,7 @@ package com.intellij.openapi.vfs.impl; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.components.NamedComponent; +import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; @@ -46,7 +46,7 @@ import org.jetbrains.annotations.TestOnly; import java.util.*; import java.util.concurrent.ConcurrentMap; -public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager implements NamedComponent, ModificationTracker, BulkFileListener, Disposable { +public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager implements ApplicationComponent, ModificationTracker, BulkFileListener { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl"); private final TempFileSystem TEMP_FILE_SYSTEM; private final LocalFileSystem LOCAL_FILE_SYSTEM; @@ -84,6 +84,15 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp JAR_FILE_SYSTEM = jarFileSystem; } + @Override + public void initComponent() { + } + + @Override + public void disposeComponent() { + assertAllPointersDisposed(); + } + @NotNull @Override public String getComponentName() { @@ -338,7 +347,6 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp @Override public void dispose() { - assertAllPointersDisposed(); } @Override From 15fb49daf8583f81c1fface1a1b0239c26516bcd Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Fri, 17 Jul 2015 18:35:47 +0200 Subject: [PATCH 039/106] =?UTF-8?q?save=20memory=20=E2=80=94=20keep=20only?= =?UTF-8?q?=20BaseComponent=20instances=20(we=20cannot=20use=20list=20of?= =?UTF-8?q?=20component=20adapters=20because=20we=20must=20dispose=20in=20?= =?UTF-8?q?reverse=20order=20of=20creation)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/impl/ComponentManagerImpl.java | 66 +++++++++---------- 1 file changed, 31 insertions(+), 35 deletions(-) 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 09260ec8e457..da402d894c27 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 @@ -131,21 +131,18 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements return myComponentsCreated; } - protected synchronized void disposeComponents() { + protected synchronized final void disposeComponents() { assert !myDisposeCompleted : "Already disposed!"; - - final List components = myComponentsRegistry == null ? Collections.emptyList() : myComponentsRegistry.getRegisteredImplementations(); myDisposed = true; + // we cannot use list of component adapters because we must dispose in reverse order of creation + List components = myComponentsRegistry == null ? Collections.emptyList() : myComponentsRegistry.myBaseComponents; for (int i = components.size() - 1; i >= 0; i--) { - Object component = components.get(i); - if (component instanceof BaseComponent) { - try { - ((BaseComponent)component).disposeComponent(); - } - catch (Throwable e) { - LOG.error(e); - } + try { + components.get(i).disposeComponent(); + } + catch (Throwable e) { + LOG.error(e); } } @@ -360,7 +357,7 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements } protected final int getComponentConfigurationsSize() { - return myComponentsRegistry.myComponentConfigsSize; + return myComponentsRegistry.myComponentConfigCount; } @Nullable @@ -394,8 +391,9 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements private final Map myInterfaceToLockMap = new THashMap(); private final List myComponentInterfaces; // keeps order of component's registration private final Map myNameToComponent = new THashMap(); - private final int myComponentConfigsSize; - private final List myImplementations = new ArrayList(); + private final int myComponentConfigCount; + private int myInstantiatedComponentCount; + private final List myBaseComponents = new ArrayList(); private final Map myComponentClassToConfig = new THashMap(); public ComponentsRegistry(@NotNull List componentConfigs) { @@ -403,7 +401,7 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements for (ComponentConfig config : componentConfigs) { registerComponents(config); } - myComponentConfigsSize = componentConfigs.size(); + myComponentConfigCount = componentConfigs.size(); } private void registerComponents(@NotNull ComponentConfig config) { @@ -444,32 +442,30 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements } private double getPercentageOfComponentsLoaded() { - return ((double)myImplementations.size()) / myComponentConfigsSize; + return ((double)myInstantiatedComponentCount) / myComponentConfigCount; } - private void registerComponentInstance(final Object component) { - myImplementations.add(component); + private void registerComponentInstance(@NotNull Object component) { + myInstantiatedComponentCount++; - if (component instanceof BaseComponent) { - BaseComponent baseComponent = (BaseComponent)component; - final String componentName = baseComponent.getComponentName(); - - if (myNameToComponent.containsKey(componentName)) { - BaseComponent loadedComponent = myNameToComponent.get(componentName); - // component may have been already loaded by PicoContainer, so fire error only if components are really different - if (!component.equals(loadedComponent)) { - LOG.error("Component name collision: " + componentName + " " + loadedComponent.getClass() + " and " + component.getClass()); - } - } - else { - myNameToComponent.put(componentName, baseComponent); + if (!(component instanceof BaseComponent)) { + return; + } + + BaseComponent baseComponent = (BaseComponent)component; + String componentName = baseComponent.getComponentName(); + if (myNameToComponent.containsKey(componentName)) { + BaseComponent loadedComponent = myNameToComponent.get(componentName); + // component may have been already loaded by PicoContainer, so fire error only if components are really different + if (!component.equals(loadedComponent)) { + LOG.error("Component name collision: " + componentName + " " + loadedComponent.getClass() + " and " + component.getClass()); } } - } + else { + myNameToComponent.put(componentName, baseComponent); + } - @NotNull - private List getRegisteredImplementations() { - return myImplementations; + myBaseComponents.add(baseComponent); } private BaseComponent getComponentByName(final String name) { From 849e8d5b66ccb4420fe43782ae8920f793710608 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 09:43:34 +0200 Subject: [PATCH 040/106] cleanup --- .../intellij/mock/MockComponentManager.java | 6 ++-- .../intellij/util/pico/IdeaPicoContainer.java | 33 ------------------- 2 files changed, 3 insertions(+), 36 deletions(-) delete mode 100644 platform/util/src/com/intellij/util/pico/IdeaPicoContainer.java diff --git a/platform/core-impl/src/com/intellij/mock/MockComponentManager.java b/platform/core-impl/src/com/intellij/mock/MockComponentManager.java index 7a7348fdbee0..4bda50500a1c 100644 --- a/platform/core-impl/src/com/intellij/mock/MockComponentManager.java +++ b/platform/core-impl/src/com/intellij/mock/MockComponentManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -61,9 +61,9 @@ public class MockComponentManager extends UserDataHolderBase implements Componen } private void registerComponentInDisposer(@Nullable Object o) { - if (o instanceof Disposable && o != MockComponentManager.this) { + if (o instanceof Disposable && o != this) { if (myDisposableComponents.add(o)) - Disposer.register(MockComponentManager.this, (Disposable)o); + Disposer.register(this, (Disposable)o); } } diff --git a/platform/util/src/com/intellij/util/pico/IdeaPicoContainer.java b/platform/util/src/com/intellij/util/pico/IdeaPicoContainer.java deleted file mode 100644 index 0131d132b9db..000000000000 --- a/platform/util/src/com/intellij/util/pico/IdeaPicoContainer.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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. - * 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.util.pico; - -import org.picocontainer.PicoContainer; - -/** - * @deprecated please use DefaultPicoContainer directly - */ -public class IdeaPicoContainer extends DefaultPicoContainer { - - public IdeaPicoContainer() { - super(null); - } - - public IdeaPicoContainer(final PicoContainer parent) { - super(parent); - } -} From 5e82ffc92a6bcbfdd892058a2157125c8853af6d Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 10:36:59 +0200 Subject: [PATCH 041/106] =?UTF-8?q?save=20memory=20=E2=80=94=20get=20rid?= =?UTF-8?q?=20of=20myInterfaceToClassMap,=20part=202=20(we=20must=20use=20?= =?UTF-8?q?instances=20only=20from=20our=20adapter=20(could=20be=20service?= =?UTF-8?q?=20or=20extension=20point=20or=20something=20else))?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ex/InspectionToolRegistrar.java | 3 +- .../src/com/intellij/mock/MockProject.java | 6 +- .../components/ex/ComponentManagerEx.java | 11 ++ .../components/impl/ComponentManagerImpl.java | 100 ++++++++++-------- .../intellij/openapi/components/service.kt | 5 +- .../ui/ChangesBrowserChangeListNode.java | 7 +- 6 files changed, 78 insertions(+), 54 deletions(-) diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionToolRegistrar.java b/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionToolRegistrar.java index 59c71ad51ab2..4e16d15e6653 100644 --- a/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionToolRegistrar.java +++ b/platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionToolRegistrar.java @@ -19,6 +19,7 @@ package com.intellij.codeInspection.ex; import com.intellij.codeInspection.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.components.ex.ComponentManagerEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.progress.ProgressManager; @@ -47,7 +48,7 @@ public class InspectionToolRegistrar { myInspectionComponentsLoaded = true; Set providers = new THashSet(); //noinspection unchecked - providers.addAll((Collection)ApplicationManager.getApplication().getPicoContainer().getComponentInstancesOfType(InspectionToolProvider.class)); + providers.addAll((((ComponentManagerEx)ApplicationManager.getApplication()).getComponentInstancesOfType(InspectionToolProvider.class))); ContainerUtil.addAll(providers, Extensions.getExtensions(InspectionToolProvider.EXTENSION_POINT_NAME)); List> factories = new ArrayList>(); registerTools(providers, factories); diff --git a/platform/core-impl/src/com/intellij/mock/MockProject.java b/platform/core-impl/src/com/intellij/mock/MockProject.java index 49a8321ff2ec..e18cbf8afc50 100644 --- a/platform/core-impl/src/com/intellij/mock/MockProject.java +++ b/platform/core-impl/src/com/intellij/mock/MockProject.java @@ -30,8 +30,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.picocontainer.PicoContainer; -import java.util.List; - /** * @author yole */ @@ -139,8 +137,8 @@ public class MockProject extends MockComponentManager implements Project { } public void projectOpened() { - //noinspection unchecked - for (ProjectComponent component : ((List)getPicoContainer().getComponentInstancesOfType(ProjectComponent.class))) { + final ProjectComponent[] components = getComponents(ProjectComponent.class); + for (ProjectComponent component : components) { try { component.projectOpened(); } diff --git a/platform/core-impl/src/com/intellij/openapi/components/ex/ComponentManagerEx.java b/platform/core-impl/src/com/intellij/openapi/components/ex/ComponentManagerEx.java index 215d5159b289..a50c1810dcb6 100644 --- a/platform/core-impl/src/com/intellij/openapi/components/ex/ComponentManagerEx.java +++ b/platform/core-impl/src/com/intellij/openapi/components/ex/ComponentManagerEx.java @@ -18,9 +18,20 @@ package com.intellij.openapi.components.ex; import com.intellij.openapi.components.ComponentManager; import org.jetbrains.annotations.NotNull; +import java.util.List; + /** * @author max */ public interface ComponentManagerEx extends ComponentManager { void initializeComponent(@NotNull Object component, boolean service); + + /** + * Gets all components whose implementation class is derived from baseClass. + * + * @return array of components + * @deprecated use extension points instead + */ + @NotNull + List getComponentInstancesOfType(@NotNull Class baseClass); } \ No newline at end of file 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 da402d894c27..fde60d96c212 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 @@ -29,6 +29,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ArrayUtil; +import com.intellij.util.ReflectionUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusFactory; @@ -237,15 +238,27 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements @Override @NotNull public T[] getComponents(@NotNull Class baseClass) { - List list = getPicoContainer().getComponentInstancesOfType(baseClass); - //noinspection unchecked - return (T[])ArrayUtil.toObjectArray(list, baseClass); + return ArrayUtil.toObjectArray(getComponentInstancesOfType(baseClass), baseClass); } @NotNull - protected final List getComponentInstancesOfType(@NotNull Class baseClass) { - //noinspection unchecked - return getPicoContainer().getComponentInstancesOfType(baseClass); + @Override + public final List getComponentInstancesOfType(@NotNull Class baseClass) { + List result = null; + // we must use instances only from our adapter (could be service or extension point or something else) + for (ComponentAdapter componentAdapter : ((DefaultPicoContainer)getPicoContainer()).getComponentAdapters()) { + if (componentAdapter instanceof ComponentConfigComponentAdapter && ReflectionUtil.isAssignable(baseClass, componentAdapter.getComponentImplementation())) { + //noinspection unchecked + T instance = (T)((ComponentConfigComponentAdapter)componentAdapter).myInitializedComponentInstance; + if (instance != null) { + if (result == null) { + result = new ArrayList(); + } + result.add(instance); + } + } + } + return ContainerUtil.notNullize(result); } @Override @@ -479,7 +492,7 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements private class ComponentConfigComponentAdapter extends ConstructorInjectionComponentAdapter { private final ComponentConfig myConfig; - private boolean myInitialized; + private volatile Object myInitializedComponentInstance; private boolean myInitializing; public ComponentConfigComponentAdapter(@NotNull ComponentConfig config, @NotNull Class implementationClass) { @@ -490,48 +503,49 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements @Override public Object getComponentInstance(PicoContainer picoContainer) throws PicoInitializationException, PicoIntrospectionException, ProcessCanceledException { - Object componentInstance = null; + Object instance = myInitializedComponentInstance; + if (instance != null) { + return instance; + } + try { long startTime = System.nanoTime(); - componentInstance = super.getComponentInstance(picoContainer); + instance = super.getComponentInstance(picoContainer); - if (!myInitialized) { - if (myInitializing) { - String errorMessage = "Cyclic component initialization: " + getComponentKey(); - if (myConfig.pluginDescriptor != null) { - LOG.error(new PluginException(errorMessage, myConfig.pluginDescriptor.getPluginId())); - } - else { - LOG.error(new Throwable(errorMessage)); - } + if (myInitializing) { + String errorMessage = "Cyclic component initialization: " + getComponentKey(); + if (myConfig.pluginDescriptor != null) { + LOG.error(new PluginException(errorMessage, myConfig.pluginDescriptor.getPluginId())); } - - try { - myInitializing = true; - myComponentsRegistry.registerComponentInstance(componentInstance); - - ProgressIndicator indicator = getProgressIndicator(); - if (indicator != null) { - indicator.checkCanceled(); - setProgressDuringInit(indicator); - } - initializeComponent(componentInstance, false); - if (componentInstance instanceof BaseComponent) { - ((BaseComponent)componentInstance).initComponent(); - } - - long ms = (System.nanoTime() - startTime) / 1000000; - if (ms > 10 && logSlowComponents()) { - LOG.info(componentInstance.getClass().getName() + " initialized in " + ms + " ms"); - } + else { + LOG.error(new Throwable(errorMessage)); } - finally { - myInitializing = false; - } - - myInitialized = true; } + + try { + myInitializing = true; + myComponentsRegistry.registerComponentInstance(instance); + + ProgressIndicator indicator = getProgressIndicator(); + if (indicator != null) { + indicator.checkCanceled(); + setProgressDuringInit(indicator); + } + initializeComponent(instance, false); + if (instance instanceof BaseComponent) { + ((BaseComponent)instance).initComponent(); + } + + long ms = (System.nanoTime() - startTime) / 1000000; + if (ms > 10 && logSlowComponents()) { + LOG.info(instance.getClass().getName() + " initialized in " + ms + " ms"); + } + } + finally { + myInitializing = false; + } + myInitializedComponentInstance = instance; } catch (ProcessCanceledException e) { throw e; @@ -543,7 +557,7 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements handleInitComponentError(t, ((String)getComponentKey()), myConfig); } - return componentInstance; + return instance; } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/components/service.kt b/platform/platform-impl/src/com/intellij/openapi/components/service.kt index 43a79eb7a82f..247b0cf2d085 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/service.kt +++ b/platform/platform-impl/src/com/intellij/openapi/components/service.kt @@ -15,6 +15,7 @@ */ package com.intellij.openapi.components +import com.intellij.openapi.components.ex.ComponentManagerEx import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.project.Project @@ -25,6 +26,4 @@ public inline fun Project.service(): T? = ServiceManager.getSer public val ComponentManager.stateStore: IComponentStore get() = getPicoContainer().getComponentInstance(javaClass()) as IComponentStore - -@suppress("UNCHECKED_CAST") -public fun ComponentManager.getComponents(baseClass: Class): List = getPicoContainer().getComponentInstancesOfType(baseClass) as List +public fun ComponentManager.getComponents(baseClass: Class): List = (this as ComponentManagerEx).getComponentInstancesOfType(baseClass) diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesBrowserChangeListNode.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesBrowserChangeListNode.java index 1a0abe87b9b0..5e35d1ca53de 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesBrowserChangeListNode.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesBrowserChangeListNode.java @@ -16,6 +16,7 @@ package com.intellij.openapi.vcs.changes.ui; +import com.intellij.openapi.components.ComponentsPackage; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vcs.changes.*; @@ -37,9 +38,7 @@ public class ChangesBrowserChangeListNode extends ChangesBrowserNode super(userObject); myChangeListRemoteState = changeListRemoteState; myClManager = (ChangeListManagerEx) ChangeListManager.getInstance(project); - - //noinspection unchecked - myDecorators = project.getPicoContainer().getComponentInstancesOfType(ChangeListDecorator.class); + myDecorators = ComponentsPackage.getComponents(project, ChangeListDecorator.class); } @Override @@ -109,11 +108,13 @@ public class ChangesBrowserChangeListNode extends ChangesBrowserNode } } + @Override public int getSortWeight() { if (userObject instanceof LocalChangeList && ((LocalChangeList)userObject).isDefault()) return 1; return 2; } + @Override public int compareUserObjects(final Object o2) { if (o2 instanceof ChangeList) { return getUserObject().getName().compareToIgnoreCase(((ChangeList)o2).getName()); From bdc5f36adfc0a17888d35938316178e5f06ae13a Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 12:53:59 +0200 Subject: [PATCH 042/106] =?UTF-8?q?don't=20keep=20component=20config=20in?= =?UTF-8?q?=20ComponentConfigComponentAdapter=20=E2=80=94=20we=20need=20on?= =?UTF-8?q?ly=20pluginId=20don't=20look=20up=20component=20during=20create?= =?UTF-8?q?Components=20=E2=80=94=20we=20have=20to=20create=20all=20our=20?= =?UTF-8?q?components,=20so,=20we=20just=20traverse=20it=20register=20comp?= =?UTF-8?q?onent=20by=20class,=20not=20by=20name,=20get=20rid=20of=20myIni?= =?UTF-8?q?tializedComponents=20map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/intellij/project/LoadProjectTest.java | 5 +- .../stores/ProjectStateStorageManager.java | 11 +- .../impl/stores/ProjectStoreImpl.java | 1 - .../openapi/components/ServiceManager.java | 13 +- .../pointers/VirtualFilePointerManager.java | 6 +- .../diagnostic/PerformanceWatcher.java | 3 +- .../components/impl/ComponentManagerImpl.java | 251 +++++++++--------- .../intellij/util/net/HttpConfigurable.java | 4 +- .../intellij/ide/plugins/PluginManager.java | 9 +- .../impl/PlatformComponentManagerImpl.java | 6 +- .../components/impl/ServiceManagerImpl.java | 8 +- .../src/META-INF/PlatformExtensions.xml | 2 + .../src/componentSets/Platform.xml | 5 - .../openapi/roots/ProjectRootManager.java | 5 +- 14 files changed, 159 insertions(+), 170 deletions(-) diff --git a/java/java-tests/testSrc/com/intellij/project/LoadProjectTest.java b/java/java-tests/testSrc/com/intellij/project/LoadProjectTest.java index 69cc43416b5b..f04dc8491ec9 100644 --- a/java/java-tests/testSrc/com/intellij/project/LoadProjectTest.java +++ b/java/java-tests/testSrc/com/intellij/project/LoadProjectTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -35,15 +35,12 @@ import com.intellij.testFramework.LeakHunter; import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl; import com.intellij.util.Processor; -import org.picocontainer.MutablePicoContainer; public class LoadProjectTest extends PlatformTestCase { @Override protected void setUpProject() throws Exception { String projectPath = PathManagerEx.getTestDataPath() + "/model/model.ipr"; myProject = ProjectManager.getInstance().loadAndOpenProject(projectPath); - MutablePicoContainer container = (MutablePicoContainer)getProject().getPicoContainer(); - container.unregisterComponent(FileEditorManager.class.getName()); ((ProjectImpl)getProject()).registerComponentImplementation(FileEditorManager.class, FileEditorManagerImpl.class); } diff --git a/platform/configuration-store-impl/src/com/intellij/openapi/components/impl/stores/ProjectStateStorageManager.java b/platform/configuration-store-impl/src/com/intellij/openapi/components/impl/stores/ProjectStateStorageManager.java index 8f9208612e36..6a4c4d047d57 100644 --- a/platform/configuration-store-impl/src/com/intellij/openapi/components/impl/stores/ProjectStateStorageManager.java +++ b/platform/configuration-store-impl/src/com/intellij/openapi/components/impl/stores/ProjectStateStorageManager.java @@ -22,8 +22,6 @@ import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Map; - public class ProjectStateStorageManager extends StateStorageManagerImpl { protected final ProjectImpl myProject; @NonNls protected static final String ROOT_TAG_NAME = "project"; @@ -53,10 +51,7 @@ public class ProjectStateStorageManager extends StateStorageManagerImpl { @Nullable @Override protected String getOldStorageSpec(@NotNull Object component, @NotNull String componentName, @NotNull StateStorageOperation operation) { - final ComponentConfig config = myProject.getConfig(component.getClass()); - assert config != null : "Couldn't find old storage for " + component.getClass().getName(); - - final boolean workspace = isWorkspace(config.options); + boolean workspace = myProject.isWorkspaceComponent(component.getClass()); String fileSpec = workspace ? StoragePathMacros.WORKSPACE_FILE : StoragePathMacros.PROJECT_FILE; StateStorage storage = getStateStorage(fileSpec, workspace ? RoamingType.DISABLED : RoamingType.PER_USER); if (operation == StateStorageOperation.READ && storage != null && workspace && !storage.hasState(component, componentName, Element.class, false)) { @@ -65,10 +60,6 @@ public class ProjectStateStorageManager extends StateStorageManagerImpl { return fileSpec; } - private static boolean isWorkspace(@Nullable Map options) { - return options != null && Boolean.parseBoolean(options.get(ProjectStoreImpl.OPTION_WORKSPACE)); - } - @NotNull @Override protected StateStorage.Listener createStorageTopicListener() { diff --git a/platform/configuration-store-impl/src/com/intellij/openapi/components/impl/stores/ProjectStoreImpl.java b/platform/configuration-store-impl/src/com/intellij/openapi/components/impl/stores/ProjectStoreImpl.java index d4135c0f1f8f..7e7426069712 100644 --- a/platform/configuration-store-impl/src/com/intellij/openapi/components/impl/stores/ProjectStoreImpl.java +++ b/platform/configuration-store-impl/src/com/intellij/openapi/components/impl/stores/ProjectStoreImpl.java @@ -60,7 +60,6 @@ public class ProjectStoreImpl extends BaseFileConfigurableStoreImpl implements I private static final Storage DEFAULT_STORAGE_ANNOTATION = new MyStorage(); @NonNls private static final String OLD_PROJECT_SUFFIX = "_old."; - @NonNls static final String OPTION_WORKSPACE = "workspace"; private static int originalVersion = -1; diff --git a/platform/core-api/src/com/intellij/openapi/components/ServiceManager.java b/platform/core-api/src/com/intellij/openapi/components/ServiceManager.java index 3731b68d78d1..ad71374ab274 100644 --- a/platform/core-api/src/com/intellij/openapi/components/ServiceManager.java +++ b/platform/core-api/src/com/intellij/openapi/components/ServiceManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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,6 +16,7 @@ package com.intellij.openapi.components; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.NotNullLazyKey; import com.intellij.util.NotNullFunction; @@ -26,15 +27,25 @@ import org.jetbrains.annotations.NotNull; * For services, there's no such contract, so we don't even load the class implementing the service until someone requests it. */ public class ServiceManager { + private static final Logger LOG = Logger.getInstance(ServiceManager.class); + private ServiceManager() { } public static T getService(@NotNull Class serviceClass) { @SuppressWarnings("unchecked") T instance = (T)ApplicationManager.getApplication().getPicoContainer().getComponentInstance(serviceClass.getName()); + if (instance == null) { + LOG.warn(serviceClass.getName() + " requested as a service, but it is a component - convert it to a service or change call to ApplicationManager.getApplication().getComponent()"); + return ApplicationManager.getApplication().getComponent(serviceClass); + } return instance; } public static T getService(@NotNull Project project, @NotNull Class serviceClass) { @SuppressWarnings("unchecked") T instance = (T)project.getPicoContainer().getComponentInstance(serviceClass.getName()); + if (instance == null) { + LOG.warn(serviceClass.getName() + " requested as a service, but it is a component - convert it to a service or change call to project.getComponent()"); + return project.getComponent(serviceClass); + } return instance; } diff --git a/platform/core-api/src/com/intellij/openapi/vfs/pointers/VirtualFilePointerManager.java b/platform/core-api/src/com/intellij/openapi/vfs/pointers/VirtualFilePointerManager.java index f727c1ce9e7d..26c5a879a1cf 100644 --- a/platform/core-api/src/com/intellij/openapi/vfs/pointers/VirtualFilePointerManager.java +++ b/platform/core-api/src/com/intellij/openapi/vfs/pointers/VirtualFilePointerManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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.openapi.vfs.pointers; import com.intellij.openapi.Disposable; -import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.SimpleModificationTracker; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; @@ -24,7 +24,7 @@ import org.jetbrains.annotations.Nullable; public abstract class VirtualFilePointerManager extends SimpleModificationTracker implements Disposable { public static VirtualFilePointerManager getInstance() { - return ServiceManager.getService(VirtualFilePointerManager.class); + return ApplicationManager.getApplication().getComponent(VirtualFilePointerManager.class); } @NotNull diff --git a/platform/core-impl/src/com/intellij/diagnostic/PerformanceWatcher.java b/platform/core-impl/src/com/intellij/diagnostic/PerformanceWatcher.java index d08786b7b062..25153b2bb058 100644 --- a/platform/core-impl/src/com/intellij/diagnostic/PerformanceWatcher.java +++ b/platform/core-impl/src/com/intellij/diagnostic/PerformanceWatcher.java @@ -19,7 +19,6 @@ import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.ApplicationComponent; -import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; @@ -66,7 +65,7 @@ public class PerformanceWatcher implements ApplicationComponent { private static final int SAMPLING_INTERVAL_MS = 1000; public static PerformanceWatcher getInstance() { - return ServiceManager.getService(PerformanceWatcher.class); + return ApplicationManager.getApplication().getComponent(PerformanceWatcher.class); } @Override 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 fde60d96c212..751a4a8dff1e 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 @@ -22,6 +22,7 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.*; import com.intellij.openapi.components.ex.ComponentManagerEx; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; @@ -52,8 +53,6 @@ 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 = ContainerUtil.newConcurrentMap(); - private boolean myComponentsCreated; private volatile MutablePicoContainer myPicoContainer; @@ -75,6 +74,7 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements myParentComponentManager = parentComponentManager; bootstrapPicoContainer(toString()); } + protected ComponentManagerImpl(@Nullable ComponentManager parentComponentManager, @NotNull String name) { myParentComponentManager = parentComponentManager; bootstrapPicoContainer(name); @@ -109,10 +109,13 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements } protected void createComponents(@Nullable ProgressIndicator indicator) { - for (Class componentInterface : myComponentsRegistry.myComponentInterfaces) { - getComponent(componentInterface); - if (indicator != null) { - indicator.checkCanceled(); + DefaultPicoContainer picoContainer = (DefaultPicoContainer)getPicoContainer(); + for (ComponentAdapter componentAdapter : picoContainer.getComponentAdapters()) { + if (componentAdapter instanceof ComponentConfigComponentAdapter) { + componentAdapter.getComponentInstance(picoContainer); + if (indicator != null) { + indicator.checkCanceled(); + } } } } @@ -151,52 +154,31 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements } @SuppressWarnings("unchecked") - @Nullable - private T getComponentFromContainer(@NotNull Class componentInterface) { - T component = (T)myInitializedComponents.get(componentInterface); - if (component != null || myDisposed) { - return component; - } - - synchronized (this) { - if (myComponentsRegistry == null) { - return null; - } - - synchronized (myComponentsRegistry.getComponentLock(componentInterface)) { - component = (T)myInitializedComponents.get(componentInterface); - if (component != null) { - return component; - } - - component = (T)getPicoContainer().getComponentInstance(componentInterface.getName()); - if (component == null) { - LOG.error("Can't instantiate component for: " + componentInterface); - } - - myInitializedComponents.put(componentInterface, component); - - if (component instanceof com.intellij.openapi.Disposable) { - Disposer.register(this, (com.intellij.openapi.Disposable)component); - } - - return component; - } - } - } - @Override public final T getComponent(@NotNull Class interfaceClass) { if (myDisposeCompleted) { ProgressManager.checkCanceled(); throw new AssertionError("Already disposed: " + this); } - return getComponent(interfaceClass, null); + + ComponentAdapter adapter = getPicoContainer().getComponentAdapter(interfaceClass); + //noinspection unchecked + if (!(adapter instanceof ComponentConfigComponentAdapter)) { + return null; + } + + if (myDisposed) { + // getComponent could be called during some component.dispose() call, in this case we don't attempt to instantiate component + return (T)((ComponentConfigComponentAdapter)adapter).myInitializedComponentInstance; + } + else { + return (T)adapter.getComponentInstance(getPicoContainer()); + } } @Override public final T getComponent(@NotNull Class interfaceClass, T defaultImplementation) { - T component = getComponentFromContainer(interfaceClass); + T component = getComponent(interfaceClass); return component == null ? defaultImplementation : component; } @@ -213,26 +195,41 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements public void initializeComponent(@NotNull Object component, boolean service) { } - protected void handleInitComponentError(Throwable ex, String componentClassName, ComponentConfig config) { + protected void handleInitComponentError(Throwable ex, String componentClassName, PluginId pluginId) { LOG.error(ex); } - public synchronized void registerComponentImplementation(@NotNull Class componentKey, @NotNull Class componentImplementation) { - getPicoContainer().registerComponentImplementation(componentKey.getName(), componentImplementation); - myInitializedComponents.remove(componentKey); + @TestOnly + public void registerComponentImplementation(@NotNull Class componentKey, @NotNull Class componentImplementation) { + MutablePicoContainer picoContainer = getPicoContainer(); + ComponentConfigComponentAdapter adapter = (ComponentConfigComponentAdapter)picoContainer.unregisterComponent(componentKey); + LOG.assertTrue(adapter != null); + picoContainer.registerComponent(new ComponentConfigComponentAdapter(componentKey, componentImplementation, null, false)); } + @SuppressWarnings("unchecked") @TestOnly public synchronized T registerComponentInstance(@NotNull Class componentKey, @NotNull T componentImplementation) { - getPicoContainer().unregisterComponent(componentKey.getName()); - getPicoContainer().registerComponentInstance(componentKey.getName(), componentImplementation); - @SuppressWarnings("unchecked") T t = (T)myInitializedComponents.remove(componentKey); - return t; + MutablePicoContainer picoContainer = getPicoContainer(); + ComponentAdapter adapter = picoContainer.getComponentAdapter(componentKey); + if (adapter instanceof ComponentConfigComponentAdapter) { + ComponentConfigComponentAdapter componentAdapter = (ComponentConfigComponentAdapter)adapter; + Object oldInstance = componentAdapter.myInitializedComponentInstance; + // we don't update pluginId - method is test only + componentAdapter.myInitializedComponentInstance = componentImplementation; + return (T)oldInstance; + } + else { + // todo it seems, it is unrealistic (illegal) case - component must have our adapter + picoContainer.unregisterComponent(componentKey); + picoContainer.registerComponentInstance(componentKey, componentImplementation); + return null; + } } @Override - public synchronized boolean hasComponent(@NotNull Class interfaceClass) { - return myComponentsRegistry != null && getPicoContainer().getComponentAdapter(interfaceClass.getName()) != null; + public boolean hasComponent(@NotNull Class interfaceClass) { + return getPicoContainer().getComponentAdapter(interfaceClass) != null; } @Override @@ -322,7 +319,6 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements myMessageBus = null; } - myInitializedComponents.clear(); myComponentsRegistry = null; myPicoContainer = null; } @@ -374,12 +370,24 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements } @Nullable - public Object getComponent(final ComponentConfig componentConfig) { - return getPicoContainer().getComponentInstance(componentConfig.getInterfaceClass()); + public final PluginId getConfig(@NotNull Class componentImplementation) { + ComponentConfigComponentAdapter adapter = getComponentAdapter(componentImplementation); + return adapter == null ? null : adapter.myPluginId; } - public ComponentConfig getConfig(Class componentImplementation) { - return myComponentsRegistry.getConfig(componentImplementation); + public final boolean isWorkspaceComponent(@NotNull Class componentImplementation) { + ComponentConfigComponentAdapter adapter = getComponentAdapter(componentImplementation); + return adapter != null && adapter.isWorkspaceComponent; + } + + @Nullable + private ComponentConfigComponentAdapter getComponentAdapter(@NotNull Class componentImplementation) { + for (ComponentAdapter componentAdapter : ((DefaultPicoContainer)getPicoContainer()).getComponentAdapters()) { + if (componentAdapter instanceof ComponentConfigComponentAdapter && componentAdapter.getComponentImplementation() == componentImplementation) { + return ((ComponentConfigComponentAdapter)componentAdapter); + } + } + return null; } @Override @@ -401,16 +409,12 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements } private class ComponentsRegistry { - private final Map myInterfaceToLockMap = new THashMap(); - private final List myComponentInterfaces; // keeps order of component's registration private final Map myNameToComponent = new THashMap(); private final int myComponentConfigCount; private int myInstantiatedComponentCount; private final List myBaseComponents = new ArrayList(); - private final Map myComponentClassToConfig = new THashMap(); public ComponentsRegistry(@NotNull List componentConfigs) { - myComponentInterfaces = new ArrayList(componentConfigs.size()); for (ComponentConfig config : componentConfigs) { registerComponents(config); } @@ -431,47 +435,39 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements throw new RuntimeException(config + " does not override anything"); } picoContainer.unregisterComponent(oldAdapter.getComponentKey()); - myComponentClassToConfig.remove(oldAdapter.getComponentImplementation()); - myComponentInterfaces.remove(interfaceClass); } // implementationClass == null means we want to unregister this component if (implementationClass != null) { - picoContainer.registerComponent(new ComponentConfigComponentAdapter(config, implementationClass)); - myComponentClassToConfig.put(implementationClass, config); - myComponentInterfaces.add(interfaceClass); + picoContainer.registerComponent(new ComponentConfigComponentAdapter(interfaceClass, implementationClass, config.getPluginId(), config.options != null && Boolean.parseBoolean(config.options.get("workspace")))); } } catch (Throwable t) { - handleInitComponentError(t, null, config); + handleInitComponentError(t, null, config.getPluginId()); } } - private Object getComponentLock(final Class componentClass) { - Object lock = myInterfaceToLockMap.get(componentClass); - if (lock == null) { - myInterfaceToLockMap.put(componentClass, lock = new Object()); - } - return lock; - } - private double getPercentageOfComponentsLoaded() { return ((double)myInstantiatedComponentCount) / myComponentConfigCount; } - private void registerComponentInstance(@NotNull Object component) { + private void registerComponentInstance(@NotNull Object instance) { myInstantiatedComponentCount++; - if (!(component instanceof BaseComponent)) { + if (instance instanceof com.intellij.openapi.Disposable) { + Disposer.register(ComponentManagerImpl.this, (com.intellij.openapi.Disposable)instance); + } + + if (!(instance instanceof BaseComponent)) { return; } - BaseComponent baseComponent = (BaseComponent)component; + BaseComponent baseComponent = (BaseComponent)instance; String componentName = baseComponent.getComponentName(); if (myNameToComponent.containsKey(componentName)) { BaseComponent loadedComponent = myNameToComponent.get(componentName); // component may have been already loaded by PicoContainer, so fire error only if components are really different - if (!component.equals(loadedComponent)) { - LOG.error("Component name collision: " + componentName + " " + loadedComponent.getClass() + " and " + component.getClass()); + if (!instance.equals(loadedComponent)) { + LOG.error("Component name collision: " + componentName + " " + loadedComponent.getClass() + " and " + instance.getClass()); } } else { @@ -484,21 +480,20 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements private BaseComponent getComponentByName(final String name) { return myNameToComponent.get(name); } - - public ComponentConfig getConfig(final Class componentImplementation) { - return myComponentClassToConfig.get(componentImplementation); - } } private class ComponentConfigComponentAdapter extends ConstructorInjectionComponentAdapter { - private final ComponentConfig myConfig; + private final PluginId myPluginId; private volatile Object myInitializedComponentInstance; private boolean myInitializing; - public ComponentConfigComponentAdapter(@NotNull ComponentConfig config, @NotNull Class implementationClass) { - super(config.getInterfaceClass(), implementationClass, null, true); + final boolean isWorkspaceComponent; - myConfig = config; + public ComponentConfigComponentAdapter(@NotNull Class interfaceClass, @NotNull Class implementationClass, @Nullable PluginId pluginId, boolean isWorkspaceComponent) { + super(interfaceClass, implementationClass, null, true); + + myPluginId = pluginId; + this.isWorkspaceComponent = isWorkspaceComponent; } @Override @@ -509,43 +504,51 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements } try { - long startTime = System.nanoTime(); - - instance = super.getComponentInstance(picoContainer); - - if (myInitializing) { - String errorMessage = "Cyclic component initialization: " + getComponentKey(); - if (myConfig.pluginDescriptor != null) { - LOG.error(new PluginException(errorMessage, myConfig.pluginDescriptor.getPluginId())); + //noinspection SynchronizeOnThis + synchronized (this) { + instance = myInitializedComponentInstance; + if (instance != null) { + return instance; } - else { - LOG.error(new Throwable(errorMessage)); + + long startTime = System.nanoTime(); + + instance = super.getComponentInstance(picoContainer); + + if (myInitializing) { + String errorMessage = "Cyclic component initialization: " + getComponentKey(); + if (myPluginId != null) { + LOG.error(new PluginException(errorMessage, myPluginId)); + } + else { + LOG.error(new Throwable(errorMessage)); + } } + + try { + myInitializing = true; + myComponentsRegistry.registerComponentInstance(instance); + + ProgressIndicator indicator = getProgressIndicator(); + if (indicator != null) { + indicator.checkCanceled(); + setProgressDuringInit(indicator); + } + initializeComponent(instance, false); + if (instance instanceof BaseComponent) { + ((BaseComponent)instance).initComponent(); + } + + long ms = (System.nanoTime() - startTime) / 1000000; + if (ms > 10 && logSlowComponents()) { + LOG.info(instance.getClass().getName() + " initialized in " + ms + " ms"); + } + } + finally { + myInitializing = false; + } + myInitializedComponentInstance = instance; } - - try { - myInitializing = true; - myComponentsRegistry.registerComponentInstance(instance); - - ProgressIndicator indicator = getProgressIndicator(); - if (indicator != null) { - indicator.checkCanceled(); - setProgressDuringInit(indicator); - } - initializeComponent(instance, false); - if (instance instanceof BaseComponent) { - ((BaseComponent)instance).initComponent(); - } - - long ms = (System.nanoTime() - startTime) / 1000000; - if (ms > 10 && logSlowComponents()) { - LOG.info(instance.getClass().getName() + " initialized in " + ms + " ms"); - } - } - finally { - myInitializing = false; - } - myInitializedComponentInstance = instance; } catch (ProcessCanceledException e) { throw e; @@ -554,7 +557,7 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements throw e; } catch (Throwable t) { - handleInitComponentError(t, ((String)getComponentKey()), myConfig); + handleInitComponentError(t, ((Class)getComponentKey()).getName(), myPluginId); } return instance; @@ -562,7 +565,7 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements @Override public String toString() { - return "ComponentConfigAdapter[" + getComponentKey() + "]: implementation=" + getComponentImplementation() + ", plugin=" + myConfig.getPluginId(); + return "ComponentConfigAdapter[" + getComponentKey() + "]: implementation=" + getComponentImplementation() + ", plugin=" + myPluginId; } } } diff --git a/platform/platform-api/src/com/intellij/util/net/HttpConfigurable.java b/platform/platform-api/src/com/intellij/util/net/HttpConfigurable.java index 43ef5e186b14..bd11ee826d4d 100644 --- a/platform/platform-api/src/com/intellij/util/net/HttpConfigurable.java +++ b/platform/platform-api/src/com/intellij/util/net/HttpConfigurable.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -104,7 +104,7 @@ public class HttpConfigurable implements PersistentStateComponent myTestGenericAuthRunnable = new StaticGetter(null); public static HttpConfigurable getInstance() { - return ServiceManager.getService(HttpConfigurable.class); + return ApplicationManager.getApplication().getComponent(HttpConfigurable.class); } public static boolean editConfigurable(@Nullable JComponent parent) { diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManager.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManager.java index 45ac584a505f..e920eed905a0 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManager.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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,7 +27,6 @@ import com.intellij.notification.Notifications; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; -import com.intellij.openapi.components.ComponentConfig; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.extensions.impl.PicoPluginExtensionInitializationException; @@ -214,7 +213,7 @@ public class PluginManager extends PluginManagerCore { return null; } - public static void handleComponentError(Throwable t, @Nullable String componentClassName, @Nullable ComponentConfig config) { + public static void handleComponentError(Throwable t, @Nullable String componentClassName, @Nullable PluginId pluginId) { Application app = ApplicationManager.getApplication(); if (app != null && app.isUnitTestMode()) { if (t instanceof Error) throw (Error)t; @@ -226,10 +225,6 @@ public class PluginManager extends PluginManagerCore { throw (StartupAbortedException)t; } - PluginId pluginId = null; - if (config != null) { - pluginId = config.getPluginId(); - } if (pluginId == null || CORE_PLUGIN_ID.equals(pluginId.getIdString())) { if (componentClassName != null) { pluginId = getPluginByClassName(componentClassName); diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/PlatformComponentManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/PlatformComponentManagerImpl.java index 312b78445c91..017288ace216 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/PlatformComponentManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/PlatformComponentManagerImpl.java @@ -16,11 +16,11 @@ package com.intellij.openapi.components.impl; import com.intellij.ide.plugins.PluginManager; -import com.intellij.openapi.components.ComponentConfig; import com.intellij.openapi.components.ComponentManager; import com.intellij.openapi.components.ComponentsPackage; import com.intellij.openapi.components.PathMacroManager; import com.intellij.openapi.components.impl.stores.IComponentStore; +import com.intellij.openapi.extensions.PluginId; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -36,11 +36,11 @@ public abstract class PlatformComponentManagerImpl extends ComponentManagerImpl } @Override - protected void handleInitComponentError(Throwable t, String componentClassName, ComponentConfig config) { + protected void handleInitComponentError(Throwable t, String componentClassName, PluginId pluginId) { if (!myHandlingInitComponentError) { myHandlingInitComponentError = true; try { - PluginManager.handleComponentError(t, componentClassName, config); + PluginManager.handleComponentError(t, componentClassName, pluginId); } finally { myHandlingInitComponentError = false; diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/ServiceManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/ServiceManagerImpl.java index 4199172b8881..97327de3b19f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/ServiceManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/ServiceManagerImpl.java @@ -15,11 +15,11 @@ */ package com.intellij.openapi.components.impl; +import com.intellij.ide.plugins.PluginManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.BaseComponent; -import com.intellij.openapi.components.ComponentConfig; import com.intellij.openapi.components.ComponentManager; import com.intellij.openapi.components.ServiceDescriptor; import com.intellij.openapi.components.ex.ComponentManagerEx; @@ -148,9 +148,9 @@ public class ServiceManagerImpl implements BaseComponent { continue; } - ComponentConfig config = componentManager.getConfig(aClass); - if (config != null) { - processor.process(aClass, config.pluginDescriptor); + PluginId pluginId = componentManager.getConfig(aClass); + if (pluginId != null) { + processor.process(aClass, PluginManager.getPlugin(pluginId)); } } } diff --git a/platform/platform-resources/src/META-INF/PlatformExtensions.xml b/platform/platform-resources/src/META-INF/PlatformExtensions.xml index b084674480f5..bdbf20ef3919 100644 --- a/platform/platform-resources/src/META-INF/PlatformExtensions.xml +++ b/platform/platform-resources/src/META-INF/PlatformExtensions.xml @@ -201,6 +201,8 @@ + + com.intellij.ide.ui.laf.HeadlessLafManagerImpl - - com.intellij.ide.UiActivityMonitor - com.intellij.ide.UiActivityMonitorImpl - - com.intellij.diagnostic.PerformanceWatcher diff --git a/platform/projectModel-api/src/com/intellij/openapi/roots/ProjectRootManager.java b/platform/projectModel-api/src/com/intellij/openapi/roots/ProjectRootManager.java index 69c7b53224e0..d808f4790c10 100644 --- a/platform/projectModel-api/src/com/intellij/openapi/roots/ProjectRootManager.java +++ b/platform/projectModel-api/src/com/intellij/openapi/roots/ProjectRootManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -15,7 +15,6 @@ */ package com.intellij.openapi.roots; -import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; @@ -40,8 +39,6 @@ public abstract class ProjectRootManager extends SimpleModificationTracker { * @return the instance. */ public static ProjectRootManager getInstance(@NotNull Project project) { - final ProjectRootManager service = ServiceManager.getService(project, ProjectRootManager.class); - if (service != null) return service; return project.getComponent(ProjectRootManager.class); } From c2ea72129fc966ddf8ae0140eb2de0ddbbb27e86 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 13:05:02 +0200 Subject: [PATCH 043/106] it is illegal to get component after component manager disposed. if for some reasons this code is still required, the actual reason of not disposed document listener must be found and issue fixed --- .../intellij/psi/impl/PsiDocumentManagerImpl.java | 6 ++++-- .../intellij/testFramework/PlatformTestCase.java | 15 +-------------- 2 files changed, 5 insertions(+), 16 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/psi/impl/PsiDocumentManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/PsiDocumentManagerImpl.java index 8d0e630b63ff..f69bd2974ae4 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/PsiDocumentManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/PsiDocumentManagerImpl.java @@ -40,6 +40,7 @@ import com.intellij.psi.impl.source.PostprocessReformattingAspect; import com.intellij.util.FileContentUtil; import com.intellij.util.Processor; import com.intellij.util.messages.MessageBus; +import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -62,7 +63,8 @@ public class PsiDocumentManagerImpl extends PsiDocumentManagerBase implements Se super(project, psiManager, bus, documentCommitThread); myDocumentCommitThread = documentCommitThread; editorFactory.getEventMulticaster().addDocumentListener(this, project); - bus.connect().subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerAdapter() { + MessageBusConnection busConnection = bus.connect(); + busConnection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerAdapter() { @Override public void fileContentLoaded(@NotNull final VirtualFile virtualFile, @NotNull Document document) { PsiFile psiFile = ApplicationManager.getApplication().runReadAction(new Computable() { @@ -74,7 +76,7 @@ public class PsiDocumentManagerImpl extends PsiDocumentManagerBase implements Se fireDocumentCreated(document, psiFile); } }); - bus.connect().subscribe(DocumentBulkUpdateListener.TOPIC, new DocumentBulkUpdateListener.Adapter() { + busConnection.subscribe(DocumentBulkUpdateListener.TOPIC, new DocumentBulkUpdateListener.Adapter() { @Override public void updateFinished(@NotNull Document doc) { documentCommitThread.queueCommit(project, doc, "Bulk update finished"); diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java index 3c59ded54879..cac76734f54f 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java @@ -31,8 +31,6 @@ import com.intellij.openapi.command.impl.UndoManagerImpl; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; -import com.intellij.openapi.editor.EditorFactory; -import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl; import com.intellij.openapi.module.EmptyModuleType; @@ -539,18 +537,7 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro result.add(e); } finally { - if (myProject != null) { - try { - PsiDocumentManager documentManager = myProject.getComponent(PsiDocumentManager.class, null); - if (documentManager != null) { - EditorFactory.getInstance().getEventMulticaster().removeDocumentListener((DocumentListener)documentManager); - } - } - catch (Exception ignored) { - - } - myProject = null; - } + myProject = null; } } From 7b72287f562a448d89b66d6c1af522ea5e1ccb31 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 13:21:00 +0200 Subject: [PATCH 044/106] DirectoryIndex as a service --- platform/platform-resources/src/META-INF/LangExtensions.xml | 3 +++ platform/platform-resources/src/componentSets/Lang.xml | 5 ----- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/platform/platform-resources/src/META-INF/LangExtensions.xml b/platform/platform-resources/src/META-INF/LangExtensions.xml index d1c46c68df45..fe7e90463bc7 100644 --- a/platform/platform-resources/src/META-INF/LangExtensions.xml +++ b/platform/platform-resources/src/META-INF/LangExtensions.xml @@ -66,6 +66,9 @@ + + diff --git a/platform/platform-resources/src/componentSets/Lang.xml b/platform/platform-resources/src/componentSets/Lang.xml index 37d7ca466c8a..fe8e0a8acfa8 100644 --- a/platform/platform-resources/src/componentSets/Lang.xml +++ b/platform/platform-resources/src/componentSets/Lang.xml @@ -51,11 +51,6 @@ com.intellij.openapi.roots.impl.ProjectRootManagerComponent - - com.intellij.openapi.roots.impl.DirectoryIndex - com.intellij.openapi.roots.impl.DirectoryIndexImpl - - com.intellij.psi.PsiManager From 78ae329ace0b327f45329d7f18aa312bd34d3dac Mon Sep 17 00:00:00 2001 From: Vyacheslav Karpukhin Date: Mon, 20 Jul 2015 15:10:57 +0200 Subject: [PATCH 045/106] Introduced XBreakpointType.createCustomPropertiesPanel(Project) method, old variant deprecated --- .../com/intellij/xdebugger/breakpoints/XBreakpointType.java | 6 ++++++ .../breakpoints/ui/XLightBreakpointPropertiesPanel.java | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java index 65ccdb14c21b..3140e1b40b33 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java @@ -144,6 +144,12 @@ public abstract class XBreakpointType, P extends XBreak } @Nullable + public XBreakpointCustomPropertiesPanel createCustomPropertiesPanel(@NotNull Project project) { + return null; + } + + @Nullable + @Deprecated public XBreakpointCustomPropertiesPanel createCustomPropertiesPanel() { return null; } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/XLightBreakpointPropertiesPanel.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/XLightBreakpointPropertiesPanel.java index b76bac76156c..a0c3901538ae 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/XLightBreakpointPropertiesPanel.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/XLightBreakpointPropertiesPanel.java @@ -165,7 +165,8 @@ public class XLightBreakpointPropertiesPanel> i } } - XBreakpointCustomPropertiesPanel customPropertiesPanel = breakpointType.createCustomPropertiesPanel(); + XBreakpointCustomPropertiesPanel customPropertiesPanel = breakpointType.createCustomPropertiesPanel(project); + if (customPropertiesPanel == null) customPropertiesPanel = breakpointType.createCustomPropertiesPanel(); if (customPropertiesPanel != null) { myCustomPropertiesPanelWrapper.add(customPropertiesPanel.getComponent(), BorderLayout.CENTER); myCustomPanels.add(customPropertiesPanel); From cc00a9667cf5780167c4a5d0394da39583fc74b3 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 16:31:33 +0200 Subject: [PATCH 046/106] MavenRehighlighter should be project service --- .../maven/indices/MavenIndicesManager.java | 6 +- .../maven/project/MavenProjectsManager.java | 4 +- .../idea/maven/utils/MavenRehighlighter.java | 107 ++++++++++-------- .../src/main/resources/META-INF/plugin.xml | 6 +- 4 files changed, 69 insertions(+), 54 deletions(-) diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndicesManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndicesManager.java index 3e00f57a9fc9..cb5c1ec75a03 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndicesManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndicesManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -258,7 +258,9 @@ public class MavenIndicesManager implements Disposable { try { getIndicesObject().updateOrRepair(each, fullUpdate, fullUpdate ? getMavenSettings(projectOrNull, indicator) : null, indicator); - if (projectOrNull != null) MavenRehighlighter.rehighlight(projectOrNull); + if (projectOrNull != null) { + MavenRehighlighter.rehighlight(projectOrNull); + } } finally { synchronized (myUpdatingIndicesLock) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java index 45fef9a8e1fb..88f9d24b06fc 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -1180,7 +1180,7 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent return projectImporter.getCreatedModules(); } - private Map getFileToModuleMapping(MavenModelsProvider modelsProvider) { + private static Map getFileToModuleMapping(MavenModelsProvider modelsProvider) { Map result = new THashMap(); for (Module each : modelsProvider.getModules()) { VirtualFile f = findPomFile(each, modelsProvider); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenRehighlighter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenRehighlighter.java index e51a3ab0b80c..b071905a5736 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenRehighlighter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenRehighlighter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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,13 +22,17 @@ import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditorManager; +import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; +import com.intellij.openapi.startup.StartupActivity; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectChanges; @@ -38,67 +42,75 @@ import org.jetbrains.idea.maven.server.NativeMavenProjectHolder; import java.util.List; -public class MavenRehighlighter extends MavenSimpleProjectComponent { - private MergingUpdateQueue myQueue; +public class MavenRehighlighter { + private final MergingUpdateQueue queue; - protected MavenRehighlighter(Project project) { - super(project); + public MavenRehighlighter(@NotNull Project project) { + queue = new MergingUpdateQueue(getClass().getSimpleName(), 1000, true, MergingUpdateQueue.ANY_COMPONENT, project, null, true); + queue.setPassThrough(false); } - public void initComponent() { - myQueue = new MergingUpdateQueue(getClass().getSimpleName(), 1000, true, MergingUpdateQueue.ANY_COMPONENT, myProject, null, true); - myQueue.setPassThrough(false); - - MavenProjectsManager m = MavenProjectsManager.getInstance(myProject); - - m.addManagerListener(new MavenProjectsManager.Listener() { - public void activated() { - rehighlight(myProject); - } - - public void projectsScheduled() { - } - - @Override - public void importAndResolveScheduled() { - } - }); - - m.addProjectsTreeListener(new MavenProjectsTree.ListenerAdapter() { - public void projectsUpdated(List> updated, List deleted) { - for (Pair each : updated) { - rehighlight(myProject, each.first); + private static final class MavenRehighlighterPostStartupActivity implements StartupActivity, DumbAware { + @Override + public void runActivity(@NotNull final Project project) { + MavenProjectsManager mavenProjectManager = MavenProjectsManager.getInstance(project); + mavenProjectManager.addManagerListener(new MavenProjectsManager.Listener() { + @Override + public void activated() { + rehighlight(project, null); } - } - public void projectResolved(Pair projectWithChanges, - NativeMavenProjectHolder nativeMavenProject) { - rehighlight(myProject, projectWithChanges.first); - } + @Override + public void projectsScheduled() { + } - public void pluginsResolved(MavenProject project) { - rehighlight(myProject, project); - } + @Override + public void importAndResolveScheduled() { + } + }); - public void foldersResolved(Pair projectWithChanges) { - rehighlight(myProject, projectWithChanges.first); - } + mavenProjectManager.addProjectsTreeListener(new MavenProjectsTree.ListenerAdapter() { + @Override + public void projectsUpdated(List> updated, List deleted) { + for (Pair each : updated) { + rehighlight(project, each.first); + } + } - public void artifactsDownloaded(MavenProject project) { - rehighlight(myProject, project); - } - }); + @Override + public void projectResolved(Pair projectWithChanges, + NativeMavenProjectHolder nativeMavenProject) { + rehighlight(project, projectWithChanges.first); + } + + @Override + public void pluginsResolved(MavenProject mavenProject) { + rehighlight(project, mavenProject); + } + + @Override + public void foldersResolved(Pair projectWithChanges) { + rehighlight(project, projectWithChanges.first); + } + + @Override + public void artifactsDownloaded(MavenProject mavenProject) { + rehighlight(project, mavenProject); + } + }); + } } - public static void rehighlight(final Project project) { + public static void rehighlight(@NotNull Project project) { rehighlight(project, null); } - public static void rehighlight(final Project project, final MavenProject mavenProject) { + public static void rehighlight(@NotNull Project project, @Nullable MavenProject mavenProject) { AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock(); try { - if (project.isDisposed()) return; - ServiceManager.getService(project, MavenRehighlighter.class).myQueue.queue(new MyUpdate(project, mavenProject)); + if (!project.isDisposed()) { + ServiceManager.getService(project, MavenRehighlighter.class).queue.queue(new MyUpdate(project, mavenProject)); + } } finally { accessToken.finish(); @@ -115,6 +127,7 @@ public class MavenRehighlighter extends MavenSimpleProjectComponent { myMavenProject = mavenProject; } + @Override public void run() { if (myMavenProject == null) { for (VirtualFile each : FileEditorManager.getInstance(myProject).getOpenFiles()) { diff --git a/plugins/maven/src/main/resources/META-INF/plugin.xml b/plugins/maven/src/main/resources/META-INF/plugin.xml index e477a5cac35a..f4f961c4c834 100644 --- a/plugins/maven/src/main/resources/META-INF/plugin.xml +++ b/plugins/maven/src/main/resources/META-INF/plugin.xml @@ -176,6 +176,9 @@ + + + @@ -329,9 +332,6 @@ org.jetbrains.idea.maven.utils.MavenImportNotifier - - org.jetbrains.idea.maven.utils.MavenRehighlighter - From a20fd64ab8909e02f125b71cf81b603df316aad2 Mon Sep 17 00:00:00 2001 From: Vyacheslav Karpukhin Date: Mon, 20 Jul 2015 16:46:41 +0200 Subject: [PATCH 047/106] Introduced XBreakpointType.createCustomPropertiesPanel(Project) method, old variant deprecated: minor rearrangements --- .../com/intellij/xdebugger/breakpoints/XBreakpointType.java | 6 ++++-- .../breakpoints/ui/XLightBreakpointPropertiesPanel.java | 1 - 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java index 3140e1b40b33..afdc8b9cac2f 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java @@ -145,11 +145,13 @@ public abstract class XBreakpointType, P extends XBreak @Nullable public XBreakpointCustomPropertiesPanel createCustomPropertiesPanel(@NotNull Project project) { - return null; + return createCustomPropertiesPanel(); } + /** + * @deprecated override {@link #createCustomPropertiesPanel(Project)} instead + */ @Nullable - @Deprecated public XBreakpointCustomPropertiesPanel createCustomPropertiesPanel() { return null; } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/XLightBreakpointPropertiesPanel.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/XLightBreakpointPropertiesPanel.java index a0c3901538ae..810b5558a6cb 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/XLightBreakpointPropertiesPanel.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/XLightBreakpointPropertiesPanel.java @@ -166,7 +166,6 @@ public class XLightBreakpointPropertiesPanel> i } XBreakpointCustomPropertiesPanel customPropertiesPanel = breakpointType.createCustomPropertiesPanel(project); - if (customPropertiesPanel == null) customPropertiesPanel = breakpointType.createCustomPropertiesPanel(); if (customPropertiesPanel != null) { myCustomPropertiesPanelWrapper.add(customPropertiesPanel.getComponent(), BorderLayout.CENTER); myCustomPanels.add(customPropertiesPanel); From 842c832ac4cbf7b27f7f8c212e1fbedd099dc918 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Mon, 20 Jul 2015 17:51:54 +0300 Subject: [PATCH 048/106] memleak: remove listener from parent window when this window is disposed --- .../intellij/ui/messages/SheetMessage.java | 34 +++++++------------ 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/ui/messages/SheetMessage.java b/platform/platform-impl/src/com/intellij/ui/messages/SheetMessage.java index 0b2eb2ecd1a2..0e82fa2ba38e 100755 --- a/platform/platform-impl/src/com/intellij/ui/messages/SheetMessage.java +++ b/platform/platform-impl/src/com/intellij/ui/messages/SheetMessage.java @@ -21,7 +21,6 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.wm.IdeFocusManager; -import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.ui.Gray; import com.intellij.ui.JBColor; import com.intellij.ui.mac.MacMainFrameDecorator; @@ -54,6 +53,17 @@ public class SheetMessage { private Image staticImage; private int imageHeight; private final boolean restoreFullScreenButton; + private final ComponentAdapter myPositionListener = new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent event) { + setPositionRelativeToParent(); + } + + @Override + public void componentMoved(ComponentEvent event) { + setPositionRelativeToParent(); + } + }; public SheetMessage(final Window owner, final String title, @@ -87,7 +97,7 @@ public class SheetMessage { myController = new SheetController(this, title, message, icon, buttons, defaultButton, doNotAskOption, focusedButton); imageHeight = 0; - registerMoveResizeHandler(); + myParent.addComponentListener(myPositionListener); myWindow.setFocusable(true); myWindow.setFocusableWindowState(true); if (SystemInfo.isJavaVersionAtLeast("1.7")) { @@ -228,6 +238,7 @@ public class SheetMessage { if (restoreFullScreenButton) { FullScreenUtilities.setWindowCanFullScreen(myParent, true); } + myParent.removeComponentListener(myPositionListener); myController.dispose(); myWindow.dispose(); } @@ -246,23 +257,4 @@ public class SheetMessage { myController.SHEET_NC_HEIGHT); } - - private void registerMoveResizeHandler () { - myParent.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(@NotNull ComponentEvent e) { - super.componentResized(e); - setPositionRelativeToParent(); - } - - @Override - public void componentMoved(@NotNull ComponentEvent e) { - super.componentMoved(e); - setPositionRelativeToParent(); - } - }); - } } - - - From 71cfbd2e8a1b0d9fa8848d5026573bb7773e3a35 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 16:41:30 +0200 Subject: [PATCH 049/106] cleanup --- .../META-INF/intellilang-xpath-support.xml | 4 --- .../inject/config/XPathSupportProxy.java | 25 ++----------------- .../inject/config/XPathSupportProxyImpl.java | 14 ++++++++--- 3 files changed, 13 insertions(+), 30 deletions(-) diff --git a/plugins/IntelliLang/src/META-INF/intellilang-xpath-support.xml b/plugins/IntelliLang/src/META-INF/intellilang-xpath-support.xml index 16caabfc5ecc..093f8148302e 100644 --- a/plugins/IntelliLang/src/META-INF/intellilang-xpath-support.xml +++ b/plugins/IntelliLang/src/META-INF/intellilang-xpath-support.xml @@ -1,10 +1,6 @@ - - - - \ No newline at end of file diff --git a/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/config/XPathSupportProxy.java b/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/config/XPathSupportProxy.java index 107335864e19..c5eae06eb8e4 100644 --- a/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/config/XPathSupportProxy.java +++ b/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/config/XPathSupportProxy.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -13,11 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.intellij.plugins.intelliLang.inject.config; import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.PsiFile; import org.jaxen.JaxenException; import org.jaxen.XPath; @@ -28,32 +26,13 @@ import org.jetbrains.annotations.Nullable; * Proxy class that allows to avoid a hard compile time dependency on the XPathView plugin. */ public abstract class XPathSupportProxy { - private static final Logger LOG = Logger.getInstance("org.intellij.plugins.intelliLang.inject.config.XPathSupportProxy"); - - public static final Object UNSUPPORTED = "UNSUPPORTED"; - public static final Object INVALID = "INVALID"; - @NotNull public abstract XPath createXPath(String expression) throws JaxenException; public abstract void attachContext(@NotNull PsiFile file); - private static XPathSupportProxy ourInstance; - private static boolean isInitialized; - @Nullable public static synchronized XPathSupportProxy getInstance() { - if (isInitialized) { - return ourInstance; - } - try { - return ourInstance = ServiceManager.getService(XPathSupportProxy.class); - } finally { - if (ourInstance == null) { - LOG.info("XPath Support is not available"); - } - isInitialized = true; - } + return ServiceManager.getService(XPathSupportProxy.class); } - } \ No newline at end of file diff --git a/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/config/XPathSupportProxyImpl.java b/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/config/XPathSupportProxyImpl.java index e581327a321f..00dff2eb6106 100644 --- a/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/config/XPathSupportProxyImpl.java +++ b/plugins/IntelliLang/xml-support/org/intellij/plugins/intelliLang/inject/config/XPathSupportProxyImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2015 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,7 @@ package org.intellij.plugins.intelliLang.inject.config; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.xml.XmlTokenImpl; import com.intellij.psi.xml.XmlElement; -import com.intellij.psi.xml.XmlElementType; +import com.intellij.psi.xml.XmlTokenType; import org.intellij.lang.xpath.context.ContextProvider; import org.intellij.lang.xpath.context.ContextType; import org.intellij.lang.xpath.context.NamespaceContext; @@ -40,13 +40,14 @@ import java.util.Set; */ public class XPathSupportProxyImpl extends XPathSupportProxy { private static class Provider extends ContextProvider { - private final XmlTokenImpl myDummyContext = new XmlTokenImpl(XmlElementType.XML_CONTENT_EMPTY, "") { + private final XmlTokenImpl myDummyContext = new XmlTokenImpl(XmlTokenType.XML_CONTENT_EMPTY, "") { @Override public boolean isValid() { return true; } }; + @Override @NotNull public ContextType getContextType() { return XPathSupport.TYPE; @@ -58,24 +59,29 @@ public class XPathSupportProxyImpl extends XPathSupportProxy { return XPathType.BOOLEAN; } + @Override public XmlElement getContextElement() { // needed because the static method ContextProvider.isValid() checks this to determine if the provider // is still valid - refactor this into an instance method ContextProvider.isValid()? return myDummyContext; } + @Override public NamespaceContext getNamespaceContext() { return null; } + @Override public VariableContext getVariableContext() { return null; } + @Override public Set getAttributes(boolean forValidation) { return null; } + @Override public Set getElements(boolean forValidation) { return null; } @@ -84,11 +90,13 @@ public class XPathSupportProxyImpl extends XPathSupportProxy { private final ContextProvider myProvider = new Provider(); private final XPathSupport mySupport = XPathSupport.getInstance(); + @Override @NotNull public XPath createXPath(String expression) throws JaxenException { return mySupport.createXPath(null, expression, Collections.emptyList()); } + @Override public void attachContext(@NotNull PsiFile file) { myProvider.attachTo(file); } From f5d4bc794c2b234244a32c65ad108330d4721a29 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 16:50:03 +0200 Subject: [PATCH 050/106] cleanup --- java/jsp-spi/src/com/intellij/psi/jsp/JspSpiUtil.java | 3 ++- .../src/com/intellij/openapi/components/ComponentManager.java | 4 +++- .../core-impl/src/com/intellij/mock/MockComponentManager.java | 1 + .../openapi/components/impl/ComponentManagerImpl.java | 1 + .../src/com/intellij/openapi/command/impl/DummyProject.java | 3 ++- 5 files changed, 9 insertions(+), 3 deletions(-) diff --git a/java/jsp-spi/src/com/intellij/psi/jsp/JspSpiUtil.java b/java/jsp-spi/src/com/intellij/psi/jsp/JspSpiUtil.java index 5f78d155c774..674fe342fbcf 100644 --- a/java/jsp-spi/src/com/intellij/psi/jsp/JspSpiUtil.java +++ b/java/jsp-spi/src/com/intellij/psi/jsp/JspSpiUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -144,6 +144,7 @@ public abstract class JspSpiUtil { public static List buildUrls(@Nullable final VirtualFile virtualFile, @Nullable final Module module, boolean includeModuleOutput) { final List urls = new ArrayList(); processClassPathItems(virtualFile, module, new Consumer() { + @Override public void consume(final VirtualFile file) { addUrl(urls, file); } diff --git a/platform/core-api/src/com/intellij/openapi/components/ComponentManager.java b/platform/core-api/src/com/intellij/openapi/components/ComponentManager.java index 32514a3348b4..41efa1d75e1e 100644 --- a/platform/core-api/src/com/intellij/openapi/components/ComponentManager.java +++ b/platform/core-api/src/com/intellij/openapi/components/ComponentManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2015 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,6 +21,7 @@ import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.UserDataHolder; import com.intellij.util.messages.MessageBus; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.picocontainer.PicoContainer; /** @@ -48,6 +49,7 @@ public interface ComponentManager extends UserDataHolder, Disposable { * @param interfaceClass the interface class of the component * @return component that matches interface class or null if there is no such component */ + @Nullable T getComponent(@NotNull Class interfaceClass); /** diff --git a/platform/core-impl/src/com/intellij/mock/MockComponentManager.java b/platform/core-impl/src/com/intellij/mock/MockComponentManager.java index 4bda50500a1c..20f951018d50 100644 --- a/platform/core-impl/src/com/intellij/mock/MockComponentManager.java +++ b/platform/core-impl/src/com/intellij/mock/MockComponentManager.java @@ -91,6 +91,7 @@ public class MockComponentManager extends UserDataHolderBase implements Componen registerComponentInDisposer(instance); } + @Nullable @Override public T getComponent(@NotNull Class interfaceClass) { final Object o = myPicoContainer.getComponentInstance(interfaceClass); 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 751a4a8dff1e..2bec610ebb76 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 @@ -153,6 +153,7 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements myComponentsCreated = false; } + @Nullable @SuppressWarnings("unchecked") @Override public final T getComponent(@NotNull Class interfaceClass) { diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/DummyProject.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/DummyProject.java index 08bd9dbbab6b..5326f56de91d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/DummyProject.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/DummyProject.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -103,6 +103,7 @@ public class DummyProject extends UserDataHolderBase implements Project { return null; } + @Nullable @Override public T getComponent(@NotNull Class interfaceClass) { return null; From 4175a49888fe7e7411a312d979a080db0f0b4448 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 16:55:21 +0200 Subject: [PATCH 051/106] warn only if instance not null (so, it is component definitly) --- .../openapi/components/ServiceManager.java | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/platform/core-api/src/com/intellij/openapi/components/ServiceManager.java b/platform/core-api/src/com/intellij/openapi/components/ServiceManager.java index ad71374ab274..ead00534b0f8 100644 --- a/platform/core-api/src/com/intellij/openapi/components/ServiceManager.java +++ b/platform/core-api/src/com/intellij/openapi/components/ServiceManager.java @@ -21,6 +21,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.NotNullLazyKey; import com.intellij.util.NotNullFunction; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * For old-style components, the contract specifies a lifecycle: the component gets created and notified during the project opening process. @@ -32,19 +33,22 @@ public class ServiceManager { private ServiceManager() { } public static T getService(@NotNull Class serviceClass) { - @SuppressWarnings("unchecked") T instance = (T)ApplicationManager.getApplication().getPicoContainer().getComponentInstance(serviceClass.getName()); - if (instance == null) { - LOG.warn(serviceClass.getName() + " requested as a service, but it is a component - convert it to a service or change call to ApplicationManager.getApplication().getComponent()"); - return ApplicationManager.getApplication().getComponent(serviceClass); - } - return instance; + return doGetService(ApplicationManager.getApplication(), serviceClass); } public static T getService(@NotNull Project project, @NotNull Class serviceClass) { - @SuppressWarnings("unchecked") T instance = (T)project.getPicoContainer().getComponentInstance(serviceClass.getName()); + return doGetService(project, serviceClass); + } + + @Nullable + private static T doGetService(@NotNull ComponentManager componentManager, @NotNull Class serviceClass) { + @SuppressWarnings("unchecked") T instance = (T)componentManager.getPicoContainer().getComponentInstance(serviceClass.getName()); if (instance == null) { - LOG.warn(serviceClass.getName() + " requested as a service, but it is a component - convert it to a service or change call to project.getComponent()"); - return project.getComponent(serviceClass); + instance = componentManager.getComponent(serviceClass); + if (instance != null) { + LOG.warn(serviceClass.getName() + " requested as a service, but it is a component - convert it to a service or change call to " + + (componentManager == ApplicationManager.getApplication() ? "ApplicationManager.getApplication().getComponent()" : "project.getComponent()")); + } } return instance; } From ad427f768e8e907bd18ae15564c2dbac120a0a8c Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 15:35:28 +0200 Subject: [PATCH 052/106] don't suggest to generate more than 100 property accessors in completion --- ...vaGenerateMemberCompletionContributor.java | 35 ++++++++++--------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaGenerateMemberCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaGenerateMemberCompletionContributor.java index e636ab4fc9b4..9c2c0aeab228 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaGenerateMemberCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaGenerateMemberCompletionContributor.java @@ -71,24 +71,27 @@ public class JavaGenerateMemberCompletionContributor { } private static void addGetterSetterElements(CompletionResultSet result, PsiClass parent, Set addedSignatures) { - List prototypes = ContainerUtil.newArrayList(); + int count = 0; for (PsiField field : parent.getFields()) { - if (!(field instanceof PsiEnumConstant)) { - Collections.addAll(prototypes, GetterSetterPrototypeProvider.generateGetterSetters(field, true)); - Collections.addAll(prototypes, GetterSetterPrototypeProvider.generateGetterSetters(field, false)); - } - } - for (final PsiMethod prototype : prototypes) { - if (parent.findMethodBySignature(prototype, false) == null && addedSignatures.add(prototype.getSignature(PsiSubstitutor.EMPTY))) { - Icon icon = prototype.getIcon(Iconable.ICON_FLAG_VISIBILITY); - result.addElement(createGenerateMethodElement(prototype, PsiSubstitutor.EMPTY, icon, "", new InsertHandler() { - @Override - public void handleInsert(InsertionContext context, LookupElement item) { - removeLookupString(context); + if (field instanceof PsiEnumConstant) continue; - insertGenerationInfos(context, Arrays.asList(new PsiGenerationInfo(prototype))); - } - })); + List prototypes = ContainerUtil.newSmartList(); + Collections.addAll(prototypes, GetterSetterPrototypeProvider.generateGetterSetters(field, true)); + Collections.addAll(prototypes, GetterSetterPrototypeProvider.generateGetterSetters(field, false)); + for (final PsiMethod prototype : prototypes) { + if (parent.findMethodBySignature(prototype, false) == null && addedSignatures.add(prototype.getSignature(PsiSubstitutor.EMPTY))) { + Icon icon = prototype.getIcon(Iconable.ICON_FLAG_VISIBILITY); + result.addElement(createGenerateMethodElement(prototype, PsiSubstitutor.EMPTY, icon, "", new InsertHandler() { + @Override + public void handleInsert(InsertionContext context, LookupElement item) { + removeLookupString(context); + + insertGenerationInfos(context, Collections.singletonList(new PsiGenerationInfo(prototype))); + } + })); + + if (count++ > 100) return; + } } } } From a524c37c2c5a2ab8978098257f79fa979eda252c Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 15:59:31 +0200 Subject: [PATCH 053/106] IDEA-142783 "*LRUMap" goto class pattern can not find SLRUMap but should --- .../com/intellij/psi/util/NameUtilMatchingTest.groovy | 4 ++++ .../src/com/intellij/psi/codeStyle/MinusculeMatcher.java | 8 ++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.groovy b/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.groovy index 57aff69321a6..d17957dc8b3e 100644 --- a/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.groovy +++ b/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.groovy @@ -334,6 +334,10 @@ public class NameUtilMatchingTest extends UsefulTestCase { assertFalse(firstLetterMatcher("*I").matches("id")); } + public void "test asterisk ending inside uppercase word"() { + assertMatches("*LRUMap", "SLRUMap"); + } + public void testMiddleMatchingFirstLetterSensitive() { assertTrue(firstLetterMatcher(" cl").matches("getClass")); assertFalse(firstLetterMatcher(" EUC-").matches("x-EUC-TW")); diff --git a/platform/util/src/com/intellij/psi/codeStyle/MinusculeMatcher.java b/platform/util/src/com/intellij/psi/codeStyle/MinusculeMatcher.java index 6a1a46effe68..f7579332bca5 100644 --- a/platform/util/src/com/intellij/psi/codeStyle/MinusculeMatcher.java +++ b/platform/util/src/com/intellij/psi/codeStyle/MinusculeMatcher.java @@ -365,7 +365,7 @@ public class MinusculeMatcher implements Matcher { return null; } - // middle matches have to be at least of length 3, to prevent too many irrelevant matches + // exact middle matches have to be at least of length 3, to prevent too many irrelevant matches int minFragment = isPatternChar(patternIndex - 1, '*') && !isWildcard(patternIndex + 1) && Character.isLetterOrDigit(name.charAt(nameIndex)) && !isWordStart(name, nameIndex) ? 3 : 1; @@ -375,11 +375,11 @@ public class MinusculeMatcher implements Matcher { patternIndex + i < myPattern.length && charEquals(myPattern[patternIndex+i], patternIndex+i, name.charAt(nameIndex + i), ignoreCase)) { if (isUpperCase[patternIndex + i] && myHasHumps) { - if (i < minFragment) { - return null; - } // when an uppercase pattern letter matches lowercase name letter, try to find an uppercase (better) match further in the name if (myPattern[patternIndex + i] != name.charAt(nameIndex + i)) { + if (i < minFragment) { + return null; + } int nextWordStart = indexOfWordStart(name, patternIndex + i, nameIndex + i); FList ranges = matchWildcards(name, patternIndex + i, nextWordStart, matchingState); if (ranges != null) { From 14be56ee7c927173bceca3fc637b5bcbf7e63148 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 16:13:50 +0200 Subject: [PATCH 054/106] MinusculeMatcher: relax digit matching --- .../com/intellij/psi/util/NameUtilMatchingTest.groovy | 2 ++ .../com/intellij/psi/codeStyle/MinusculeMatcher.java | 11 +++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.groovy b/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.groovy index d17957dc8b3e..ccf973962b0e 100644 --- a/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.groovy +++ b/platform/platform-tests/testSrc/com/intellij/psi/util/NameUtilMatchingTest.groovy @@ -430,6 +430,8 @@ public class NameUtilMatchingTest extends UsefulTestCase { assertMatches("*TEST-* ", "TEST-001"); assertMatches("*TEST-0* ", "TEST-001"); assertMatches("*v2 ", "VARCHAR2"); + assertMatches("smart8co", "SmartType18CompletionTest"); + assertMatches("smart8co", "smart18completion"); } public void testSpecialSymbols() { diff --git a/platform/util/src/com/intellij/psi/codeStyle/MinusculeMatcher.java b/platform/util/src/com/intellij/psi/codeStyle/MinusculeMatcher.java index f7579332bca5..fb5f7bd07e6b 100644 --- a/platform/util/src/com/intellij/psi/codeStyle/MinusculeMatcher.java +++ b/platform/util/src/com/intellij/psi/codeStyle/MinusculeMatcher.java @@ -117,6 +117,13 @@ public class MinusculeMatcher implements Matcher { return i == 0 || !Character.isLetterOrDigit(text.charAt(i - 1)); } + private static int nextWord(@NotNull String name, int start) { + if (start < name.length() && Character.isDigit(name.charAt(start))) { + return start + 1; //treat each digit as a separate hump + } + return NameUtil.nextWord(name, start); + } + private boolean hasWildCards() { for (int i = 0; i < myPattern.length; i++) { if (isWildcard(i)) { @@ -177,7 +184,7 @@ public class MinusculeMatcher implements Matcher { if (nextHumpStart == i) { isHumpStart = true; } - nextHumpStart = NameUtil.nextWord(name, nextHumpStart); + nextHumpStart = nextWord(name, nextHumpStart); if (first != range) { humpIndex++; } @@ -457,7 +464,7 @@ public class MinusculeMatcher implements Matcher { } int nextWordStart = startFrom; while (true) { - nextWordStart = NameUtil.nextWord(name, nextWordStart); + nextWordStart = nextWord(name, nextWordStart); if (nextWordStart >= name.length()) { return -1; } From 1b70adbfd49e00194c4c1170ef65e8114d7a2e46 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 16:54:31 +0200 Subject: [PATCH 055/106] IDEA-137195 Not annotated constant fields should be treated as Nullable or NotNull when static code analysis is able to prove Nullable/NotNull --- .../dataFlow/DataFlowInspectionBase.java | 40 ++++++++-- .../codeInspection/dataFlow/DfaPsiUtil.java | 4 + .../dataFlow/value/DfaVariableValue.java | 29 ++++--- .../FinalFieldNotDuringInitialization.java | 79 +++++++++++++++++++ .../DataFlowInspectionTest.java | 10 +++ 5 files changed, 145 insertions(+), 17 deletions(-) create mode 100644 java/java-tests/testData/inspection/dataFlow/fixture/FinalFieldNotDuringInitialization.java diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java index bed3e5b67ac8..bca5390a66ee 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java @@ -35,6 +35,7 @@ import com.intellij.codeInspection.dataFlow.instructions.*; import com.intellij.codeInspection.dataFlow.value.DfaConstValue; import com.intellij.codeInspection.dataFlow.value.DfaValue; import com.intellij.codeInspection.nullable.NullableStuffInspectionBase; +import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; @@ -43,14 +44,12 @@ import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; +import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.refactoring.extractMethod.ExtractMethodUtil; -import com.intellij.util.ArrayUtil; -import com.intellij.util.ArrayUtilRt; -import com.intellij.util.IncorrectOperationException; -import com.intellij.util.SmartList; +import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import org.jdom.Element; @@ -157,11 +156,42 @@ public class DataFlowInspectionBase extends BaseJavaBatchLocalInspectionTool { while (element != null) { element = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiClassInitializer.class); if (element instanceof PsiClassInitializer) return true; - if (element instanceof PsiMethod && ((PsiMethod)element).isConstructor()) return true; + if (element instanceof PsiMethod) { + if (((PsiMethod)element).isConstructor()) return true; + + final PsiClass containingClass = ((PsiMethod)element).getContainingClass(); + return !InheritanceUtil.processSupers(containingClass, true, new Processor() { + @Override + public boolean process(PsiClass psiClass) { + return !canCallMethodsInConstructors(psiClass, psiClass != containingClass); + } + }); + + } } return false; } + private static boolean canCallMethodsInConstructors(PsiClass aClass, boolean virtual) { + for (PsiMethod constructor : aClass.getConstructors()) { + if (!constructor.getLanguage().isKindOf(JavaLanguage.INSTANCE)) return true; + + PsiCodeBlock body = constructor.getBody(); + if (body == null) continue; + + for (PsiMethodCallExpression call : SyntaxTraverser.psiTraverser().withRoot(body).filter(PsiMethodCallExpression.class)) { + PsiReferenceExpression methodExpression = call.getMethodExpression(); + if (methodExpression instanceof PsiThisExpression || methodExpression instanceof PsiSuperExpression) continue; + if (!virtual) return true; + + PsiMethod target = call.resolveMethod(); + if (target != null && PsiUtil.canBeOverriden(target)) return true; + } + } + + return false; + } + private void analyzeDfaWithNestedClosures(PsiElement scope, ProblemsHolder holder, StandardDataFlowRunner dfaRunner, diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaPsiUtil.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaPsiUtil.java index 987054ad360a..4c78c4807069 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaPsiUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DfaPsiUtil.java @@ -70,6 +70,10 @@ public class DfaPsiUtil { return Nullness.UNKNOWN; } + if (owner instanceof PsiEnumConstant) { + return Nullness.NOT_NULL; + } + if (resultType != null) { NullableNotNullManager nnn = NullableNotNullManager.getInstance(owner.getProject()); for (PsiAnnotation annotation : resultType.getAnnotations()) { diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaVariableValue.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaVariableValue.java index fd45fdfc8b5a..f8f6d16aed13 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaVariableValue.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaVariableValue.java @@ -24,7 +24,6 @@ */ package com.intellij.codeInspection.dataFlow.value; -import com.intellij.codeInsight.NullableNotNullManager; import com.intellij.codeInsight.daemon.impl.analysis.JavaGenericsUtil; import com.intellij.codeInspection.dataFlow.DfaPsiUtil; import com.intellij.codeInspection.dataFlow.Nullness; @@ -195,19 +194,11 @@ public class DfaVariableValue extends DfaValue { boolean hasUnknowns = false; for (PsiExpression expression : initializers) { - if (!(expression instanceof PsiReferenceExpression)) { - hasUnknowns = true; - continue; - } - PsiElement target = ((PsiReferenceExpression)expression).resolve(); - if (!(target instanceof PsiParameter)) { - hasUnknowns = true; - continue; - } - if (NullableNotNullManager.isNullable((PsiParameter)target)) { + Nullness nullness = getFieldInitializerNullness(expression); + if (nullness == Nullness.NULLABLE) { return Nullness.NULLABLE; } - if (!NullableNotNullManager.isNotNull((PsiParameter)target)) { + if (nullness == Nullness.UNKNOWN) { hasUnknowns = true; } } @@ -225,6 +216,20 @@ public class DfaVariableValue extends DfaValue { return defaultNullability; } + private static Nullness getFieldInitializerNullness(@NotNull PsiExpression expression) { + if (expression.textMatches(PsiKeyword.NULL)) return Nullness.NULLABLE; + if (expression instanceof PsiNewExpression || expression instanceof PsiLiteralExpression || expression instanceof PsiPolyadicExpression) return Nullness.NOT_NULL; + if (expression instanceof PsiReferenceExpression) { + PsiElement target = ((PsiReferenceExpression)expression).resolve(); + return DfaPsiUtil.getElementNullability(null, (PsiModifierListOwner)target); + } + if (expression instanceof PsiMethodCallExpression) { + PsiMethod method = ((PsiMethodCallExpression)expression).resolveMethod(); + return method != null ? DfaPsiUtil.getElementNullability(null, method) : Nullness.UNKNOWN; + } + return Nullness.UNKNOWN; + } + public boolean isFlushableByCalls() { if (myVariable instanceof PsiLocalVariable || myVariable instanceof PsiParameter) return false; if (myVariable instanceof PsiVariable && myVariable.hasModifierProperty(PsiModifier.FINAL)) { diff --git a/java/java-tests/testData/inspection/dataFlow/fixture/FinalFieldNotDuringInitialization.java b/java/java-tests/testData/inspection/dataFlow/fixture/FinalFieldNotDuringInitialization.java new file mode 100644 index 000000000000..91b8d23ee0b2 --- /dev/null +++ b/java/java-tests/testData/inspection/dataFlow/fixture/FinalFieldNotDuringInitialization.java @@ -0,0 +1,79 @@ +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +class Super { + public Super() { + this(2); + } + + public Super(int a) { + staticMethod(); + } + + static void staticMethod() {} + +} + +class Test { + @Nullable + private static Object getNull() { + return null; + } + + private static final Object CONST = getNull(); + + public static void test() { + System.out.println(CONST.toString()); + } +} + +class Test2 extends Super { + @NotNull + private static Object getNotNull() { + return new Object(); + } + + private static final Object CONST = getNotNull(); + + public static void test() { + System.out.println(CONST.toString()); + } +} + +class Test3 { + + private static final Object CONST = ""; + + public static void test() { + System.out.println(CONST.toString()); + } +} + +class Test4 { + + public enum Day { + SUNDAY, MONDAY, TUESDAY, WEDNESDAY, + THURSDAY, FRIDAY, SATURDAY + } + + private static final Day CONST = Day.FRIDAY; + + public static void test() { + System.out.println(CONST.toString()); + } +} + +class Test5 { + private final String something = new String("something"); + private final String somethingElse = "somethingElse"; + + public Integer someLength() { + //May produce nullpointer warning + return something.length(); + } + + public Integer someElseLength() { + //No warning + return somethingElse.length(); + } +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java index 362c04ee0766..3c5913134981 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java @@ -196,6 +196,16 @@ public class DataFlowInspectionTest extends LightCodeInsightFixtureTestCase { public void testFinalFieldDuringInitialization() { doTest(); } public void testFinalFieldDuringSuperInitialization() { doTest(); } public void testFinalFieldInConstructorAnonymous() { doTest(); } + + public void testFinalFieldNotDuringInitialization() { + final DataFlowInspection inspection = new DataFlowInspection(); + inspection.TREAT_UNKNOWN_MEMBERS_AS_NULLABLE = true; + inspection.REPORT_CONSTANT_REFERENCE_VALUES = false; + myFixture.enableInspections(inspection); + myFixture.testHighlighting(true, false, true, getTestName(false) + ".java"); + } + + public void _testSymmetricUncheckedCast() { doTest(); } // https://youtrack.jetbrains.com/issue/IDEABKL-6871 public void testNullCheckDoesntAffectUncheckedCast() { doTest(); } public void testThrowNull() { doTest(); } From 934bf974f8bf55392470a258fe276519ac0844ce Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 17:03:51 +0200 Subject: [PATCH 056/106] IDEA-128290 Allow cancelling directory creation if specified name contains dot --- .../actions/CreateDirectoryOrPackageHandler.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java b/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java index bd6318e7ba31..f5c99d5b9f09 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java @@ -159,10 +159,15 @@ public class CreateDirectoryOrPackageHandler implements InputValidatorEx { FileType fileType = findFileTypeBoundToName(subDirName); if (fileType != null) { String message = "The name you entered looks like a file name. Do you want to create a file named " + subDirName + " instead?"; - int ec = Messages.showYesNoDialog(myProject, message, - "File Name Detected", "Yes, create file", - "No, create " + (myIsDirectory ? "directory" : "packages"), - fileType.getIcon()); + int ec = Messages.showYesNoCancelDialog(myProject, message, + "File Name Detected", + "&Yes, create file", + "&No, create " + (myIsDirectory ? "directory" : "packages"), + "&Cancel", + fileType.getIcon()); + if (ec == Messages.CANCEL) { + return false; + } if (ec == Messages.YES) { createFile = true; } From 26820cfdf0fee55b0e00c986c7a2a49f9195f7d2 Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Mon, 20 Jul 2015 17:28:36 +0200 Subject: [PATCH 057/106] don't delete bundled plugins when installing an updated plugin with the same ID from the plugin repo --- .../com/intellij/ide/plugins/InstalledPluginsManagerMain.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java b/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java index 3db4fa984776..f215b2f899ad 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java @@ -151,7 +151,7 @@ public class InstalledPluginsManagerMain extends PluginManagerMain { } IdeaPluginDescriptor installedPlugin = PluginManager.getPlugin(pluginDescriptor.getPluginId()); - if (installedPlugin != null) { + if (installedPlugin != null && !installedPlugin.isBundled()) { File oldFile = installedPlugin.getPath(); if (oldFile != null) { StartupActionScriptManager.addActionCommand(new StartupActionScriptManager.DeleteCommand(oldFile)); From 5350d007fa44581d62fe476bfd91f001b95ef53f Mon Sep 17 00:00:00 2001 From: Julia Beliaeva Date: Mon, 20 Jul 2015 18:27:01 +0300 Subject: [PATCH 058/106] [vcs-log] tmp fix for slow table repaint --- .../vcs/log/ui/MyCommitsHighlighter.java | 35 +++++++++++++++---- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/MyCommitsHighlighter.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/MyCommitsHighlighter.java index ea0263e71391..e49ac7ca572d 100644 --- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/MyCommitsHighlighter.java +++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/MyCommitsHighlighter.java @@ -15,26 +15,28 @@ */ package com.intellij.vcs.log.ui; -import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.util.NotNullFunction; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcs.log.*; import com.intellij.vcs.log.data.LoadingDetails; import com.intellij.vcs.log.data.VcsLogDataHolder; import com.intellij.vcs.log.data.VcsLogUiProperties; +import com.intellij.vcs.log.impl.VcsLogContentProvider; +import com.intellij.vcs.log.impl.VcsLogManager; import com.intellij.vcs.log.impl.VcsUserImpl; import com.intellij.vcs.log.ui.filter.VcsLogUserFilterImpl; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Collections; -import java.util.Map; import java.util.Set; public class MyCommitsHighlighter implements VcsLogHighlighter { @NotNull private final VcsLogUiProperties myUiProperties; @NotNull private final VcsLogDataHolder myDataHolder; @NotNull private final VcsLogFilterUi myFilterUi; + private boolean myAreTheOnlyUsers = false; public MyCommitsHighlighter(@NotNull VcsLogDataHolder logDataHolder, @NotNull VcsLogUiProperties uiProperties, @@ -49,17 +51,36 @@ public class MyCommitsHighlighter implements VcsLogHighlighter { myUiProperties.enableHighlighter(Factory.ID, false); myUiProperties.setHighlightMyCommits(true); } + + // this is a tmp solution for performance problems of calculating areTheOnlyUsers every repaint (we simply do not want to do that) + // todo remove this when history2 branch is merged into master (history2 will allow a proper way to fix the problem) + ApplicationManager.getApplication().invokeLater(new Runnable() { + @Override + public void run() { + VcsLogManager logManager = VcsLogContentProvider.findLogManager(myDataHolder.getProject()); + if (logManager != null) { + VcsLogUiImpl logUi = logManager.getLogUi(); + if (logUi != null) { + logUi.addLogListener(new VcsLogListener() { + @Override + public void onChange(@NotNull VcsLogDataPack dataPack, boolean refreshHappened) { + myAreTheOnlyUsers = areTheOnlyUsers(); + } + }); + } + } + } + }); } @NotNull @Override public VcsCommitStyle getStyle(int commitIndex, boolean isSelected) { if (!myUiProperties.isHighlighterEnabled(Factory.ID)) return VcsCommitStyle.DEFAULT; - Map currentUsers = myDataHolder.getCurrentUser(); - if (!areTheOnlyUsers(currentUsers) && !isFilteredByCurrentUser()) { + if (!myAreTheOnlyUsers && !isFilteredByCurrentUser()) { VcsShortCommitDetails details = myDataHolder.getMiniDetailsGetter().getCommitDataIfAvailable(commitIndex); if (details != null && !(details instanceof LoadingDetails)) { - VcsUser currentUser = currentUsers.get(details.getRoot()); + VcsUser currentUser = myDataHolder.getCurrentUser().get(details.getRoot()); if (currentUser != null && VcsUserImpl.isSamePerson(currentUser, details.getAuthor())) { return VcsCommitStyleFactory.bold(); } @@ -68,7 +89,7 @@ public class MyCommitsHighlighter implements VcsLogHighlighter { return VcsCommitStyle.DEFAULT; } - private boolean areTheOnlyUsers(@NotNull Map currentUsers) { + private boolean areTheOnlyUsers() { NotNullFunction nameToString = new NotNullFunction() { @NotNull @Override @@ -77,7 +98,7 @@ public class MyCommitsHighlighter implements VcsLogHighlighter { } }; Set allUserNames = ContainerUtil.newHashSet(ContainerUtil.map(myDataHolder.getAllUsers(), nameToString)); - Set currentUserNames = ContainerUtil.newHashSet(ContainerUtil.map(currentUsers.values(), nameToString)); + Set currentUserNames = ContainerUtil.newHashSet(ContainerUtil.map(myDataHolder.getCurrentUser().values(), nameToString)); return allUserNames.size() == currentUserNames.size() && currentUserNames.containsAll(allUserNames); } From 9d1b9ed314274a6358025a3dcef06b2abd413582 Mon Sep 17 00:00:00 2001 From: Aleksey Pivovarov Date: Mon, 20 Jul 2015 15:11:04 +0300 Subject: [PATCH 059/106] diff: CopyableLabel does not support html highlighting yet strip it instead. --- .../diff-impl/src/com/intellij/diff/util/CopyableLabel.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/platform/diff-impl/src/com/intellij/diff/util/CopyableLabel.java b/platform/diff-impl/src/com/intellij/diff/util/CopyableLabel.java index 6826a64ec15a..11f9f1453d55 100644 --- a/platform/diff-impl/src/com/intellij/diff/util/CopyableLabel.java +++ b/platform/diff-impl/src/com/intellij/diff/util/CopyableLabel.java @@ -16,6 +16,7 @@ package com.intellij.diff.util; import com.intellij.openapi.util.registry.Registry; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; @@ -57,7 +58,7 @@ public class CopyableLabel extends JTextArea { setBackground(UIUtil.TRANSPARENT_COLOR); setBorder(null); setOpaque(false); - setText(text); + setText(StringUtil.stripHtml(text, false)); setCaretPosition(0); } From b22b375f415728124f3bf59c157d15fb07f5f28f Mon Sep 17 00:00:00 2001 From: Aleksey Pivovarov Date: Mon, 20 Jul 2015 16:58:29 +0300 Subject: [PATCH 060/106] editor: do not check GutterIconRenderer for DumbAware. check it's AnAction instead. --- .../editor/markup/GutterIconRenderer.java | 2 - .../impl/EditorGutterComponentImpl.java | 42 ++++++++++--------- 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/platform/editor-ui-api/src/com/intellij/openapi/editor/markup/GutterIconRenderer.java b/platform/editor-ui-api/src/com/intellij/openapi/editor/markup/GutterIconRenderer.java index ad865eae4bed..bb1e6b416bad 100644 --- a/platform/editor-ui-api/src/com/intellij/openapi/editor/markup/GutterIconRenderer.java +++ b/platform/editor-ui-api/src/com/intellij/openapi/editor/markup/GutterIconRenderer.java @@ -31,8 +31,6 @@ import javax.swing.*; * Daemon code analyzer checks newly arrived gutter icon renderer against the old one and if they are equal, does not redraw the icon. * So it is highly advisable to override hashCode()/equals() methods to avoid icon flickering when old gutter renderer gets replaced with the new.

* - * During indexing, click handlers are only invoked for renderers implementing {@link com.intellij.openapi.project.DumbAware}. - * * @author max * @see RangeHighlighter#setGutterIconRenderer(GutterIconRenderer) */ 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 e6478f35555a..e429a590ce6c 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 @@ -1368,8 +1368,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse private boolean isPopupAction(MouseEvent e) { GutterIconRenderer renderer = getGutterRenderer(e); - return renderer != null && !isNavigationBlocked(renderer, myEditor.getProject()) && - renderer.getClickAction() == null && renderer.getPopupMenuActions() != null; + return renderer != null && renderer.getClickAction() == null && renderer.getPopupMenuActions() != null; } @Override @@ -1381,10 +1380,6 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse GutterIconRenderer renderer = getGutterRenderer(e); final Project project = myEditor.getProject(); - if (renderer != null && isNavigationBlocked(renderer, project)) { - DumbService.getInstance(project).showDumbModeNotification("Navigation is not available during indexing"); - return; - } AnAction clickAction = null; if (renderer != null && e.getButton() < 4) { @@ -1393,11 +1388,13 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse : renderer.getClickAction(); } if (clickAction != null) { - clickAction.actionPerformed(new AnActionEvent(e, myEditor.getDataContext(), "ICON_NAVIGATION", clickAction.getTemplatePresentation(), - ActionManager.getInstance(), - e.getModifiers())); + if (checkActionNotBlocked(clickAction, project)) { + clickAction.actionPerformed(new AnActionEvent(e, myEditor.getDataContext(), "ICON_NAVIGATION", clickAction.getTemplatePresentation(), + ActionManager.getInstance(), + e.getModifiers())); + repaint(); + } e.consume(); - repaint(); } else { ActiveGutterRenderer lineRenderer = getActiveRendererByMouseEvent(e); @@ -1409,8 +1406,10 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse } } - private static boolean isNavigationBlocked(@NotNull GutterIconRenderer renderer, @Nullable Project project) { - return project != null && DumbService.isDumb(project) && !DumbService.isDumbAware(renderer); + private static boolean checkActionNotBlocked(@NotNull AnAction action, @Nullable Project project) { + if (project == null || !DumbService.isDumb(project) || action.isDumbAware()) return true; + DumbService.getInstance(project).showDumbModeNotification("Action is not available during indexing"); + return false; } @Nullable @@ -1552,16 +1551,21 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse if (renderer != null) { ActionGroup actionGroup = renderer.getPopupMenuActions(); if (actionGroup != null) { - ActionPopupMenu popupMenu = actionManager.createActionPopupMenu(ActionPlaces.UNKNOWN, - actionGroup); - popupMenu.getComponent().show(this, e.getX(), e.getY()); + if (checkActionNotBlocked(actionGroup, myEditor.getProject())) { + ActionPopupMenu popupMenu = actionManager.createActionPopupMenu(ActionPlaces.UNKNOWN, + actionGroup); + popupMenu.getComponent().show(this, e.getX(), e.getY()); + } e.consume(); - } else { + } + else { AnAction rightButtonAction = renderer.getRightButtonClickAction(); if (rightButtonAction != null) { - rightButtonAction.actionPerformed(new AnActionEvent(e, myEditor.getDataContext(), "ICON_NAVIGATION_SECONDARY_BUTTON", rightButtonAction.getTemplatePresentation(), - ActionManager.getInstance(), - e.getModifiers())); + if (checkActionNotBlocked(rightButtonAction, myEditor.getProject())) { + rightButtonAction.actionPerformed(new AnActionEvent(e, myEditor.getDataContext(), "ICON_NAVIGATION_SECONDARY_BUTTON", rightButtonAction.getTemplatePresentation(), + ActionManager.getInstance(), + e.getModifiers())); + } e.consume(); } } From 3da07b7af27f1f7c3bb58b7500f17b67ad2a8b02 Mon Sep 17 00:00:00 2001 From: Aleksey Pivovarov Date: Mon, 20 Jul 2015 14:47:36 +0300 Subject: [PATCH 061/106] diff: mark chevrone actions as DumbAware --- .../com/intellij/openapi/diff/actions/MergeActionGroup.java | 3 ++- .../openapi/diff/impl/incrementalMerge/MergeList.java | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/actions/MergeActionGroup.java b/platform/platform-impl/src/com/intellij/openapi/diff/actions/MergeActionGroup.java index 02fb68bc09a6..908238373d23 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/actions/MergeActionGroup.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/actions/MergeActionGroup.java @@ -19,6 +19,7 @@ import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.diff.DiffBundle; import com.intellij.openapi.diff.impl.DiffPanelImpl; import com.intellij.openapi.diff.impl.highlighting.FragmentSide; +import com.intellij.openapi.project.DumbAwareAction; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -64,7 +65,7 @@ public class MergeActionGroup extends ActionGroup { } } - public static class OperationAction extends AnAction { + public static class OperationAction extends DumbAwareAction { private final MergeOperations.Operation myOperation; public OperationAction(MergeOperations.Operation operation) { diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java index 583b08547646..106daac84ee8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/MergeList.java @@ -33,6 +33,7 @@ import com.intellij.openapi.diff.impl.util.ContextLogger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.DocumentEx; +import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.util.containers.ContainerUtil; @@ -236,13 +237,13 @@ public class MergeList implements UserDataHolder { for (int i = 0; i < changeList.getCount(); i++) { final Change change = changeList.getChange(i); if (!change.canHasActions(originalSide)) continue; - AnAction applyAction = new AnAction(DiffBundle.message("merge.dialog.apply.change.action.name"), null, AllIcons.Diff.Arrow) { + AnAction applyAction = new DumbAwareAction(DiffBundle.message("merge.dialog.apply.change.action.name"), null, AllIcons.Diff.Arrow) { @Override public void actionPerformed(@Nullable AnActionEvent e) { apply(change); } }; - AnAction ignoreAction = new AnAction(DiffBundle.message("merge.dialog.ignore.change.action.name"), null, AllIcons.Diff.Remove) { + AnAction ignoreAction = new DumbAwareAction(DiffBundle.message("merge.dialog.ignore.change.action.name"), null, AllIcons.Diff.Remove) { @Override public void actionPerformed(@Nullable AnActionEvent e) { change.removeFromList(); From 5f758f81c523adb6e4c3920ee36e023a873797a8 Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Mon, 20 Jul 2015 19:31:01 +0200 Subject: [PATCH 062/106] "Optimize imports" usually optimizes more than one import --- .../platform-resources-en/src/messages/ActionsBundle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/platform-resources-en/src/messages/ActionsBundle.properties b/platform/platform-resources-en/src/messages/ActionsBundle.properties index 52e251ea973c..707582f42f96 100644 --- a/platform/platform-resources-en/src/messages/ActionsBundle.properties +++ b/platform/platform-resources-en/src/messages/ActionsBundle.properties @@ -545,7 +545,7 @@ action.ReformatCode.text=_Reformat Code action.ReformatCode.description=Reformat code action.AutoIndentLines.text=_Auto-Indent Lines action.AutoIndentLines.description=Indent current line or selected block according to the code style settings -action.OptimizeImports.text=Optimi_ze Import +action.OptimizeImports.text=Optimi_ze Imports action.OptimizeImports.description=Remove unused imports and reorder/reorganize imports action.RearrangeCode.text=Rearrange Code action.RearrangeCode.description=Rearrange code From dbd6f4e66d67b92fdb22af2ce6dedae0566f65e0 Mon Sep 17 00:00:00 2001 From: "Egor.Ushakov" Date: Mon, 20 Jul 2015 20:34:42 +0300 Subject: [PATCH 063/106] reverted transparent progress in completion for Peter, see IDEA-142801 --- .../codeInsight/lookup/impl/LookupUi.java | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupUi.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupUi.java index 53c6c19268d7..3049f6d816b0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupUi.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupUi.java @@ -47,6 +47,7 @@ import com.intellij.ui.components.JBScrollPane; import com.intellij.util.Alarm; import com.intellij.util.PlatformIcons; import com.intellij.util.ui.AbstractLayoutManager; +import com.intellij.util.ui.AsyncProcessIcon; import com.intellij.util.ui.ButtonlessScrollBarUI; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; @@ -77,6 +78,8 @@ class LookupUi { private final JLabel mySortingLabel = new JLabel(); private final JScrollPane myScrollPane; private final JButton myScrollBarIncreaseButton; + private final AsyncProcessIcon myProcessIcon = new AsyncProcessIcon("Completion progress"); + private final JPanel myIconPanel = new JPanel(new BorderLayout()); private final LookupLayeredPane myLayeredPane = new LookupLayeredPane(); private LookupHint myElementHint = null; @@ -89,6 +92,10 @@ class LookupUi { myList = list; myProject = project; + myIconPanel.setVisible(false); + myIconPanel.setBackground(Color.LIGHT_GRAY); + myIconPanel.add(myProcessIcon); + JComponent adComponent = advertiser.getAdComponent(); adComponent.setBorder(new EmptyBorder(0, 1, 1, 2 + AllIcons.Ide.LookupRelevance.getIconWidth())); myLayeredPane.mainPanel.add(adComponent, BorderLayout.SOUTH); @@ -125,6 +132,7 @@ class LookupUi { updateScrollbarVisibility(); + Disposer.register(lookup, myProcessIcon); Disposer.register(lookup, myHintAlarm); } @@ -220,7 +228,7 @@ class LookupUi { Runnable setVisible = new Runnable() { @Override public void run() { - myList.setPaintBusy(myLookup.isCalculating()); + myIconPanel.setVisible(myLookup.isCalculating()); } }; if (myLookup.isCalculating()) { @@ -228,6 +236,12 @@ class LookupUi { } else { setVisible.run(); } + + if (calculating) { + myProcessIcon.resume(); + } else { + myProcessIcon.suspend(); + } } private void updateSorting() { @@ -325,6 +339,7 @@ class LookupUi { private LookupLayeredPane() { add(mainPanel, 0, 0); + add(myIconPanel, 42, 0); add(mySortingLabel, 10, 0); setLayout(new AbstractLayoutManager() { @@ -379,6 +394,10 @@ class LookupUi { vScrollBar.revalidate(); vScrollBar.repaint(); + final Dimension iconSize = myProcessIcon.getPreferredSize(); + myIconPanel.setBounds(getWidth() - iconSize.width - (vScrollBar.isVisible() ? vScrollBar.getWidth() : 0), 0, iconSize.width, + iconSize.height); + final Dimension sortSize = mySortingLabel.getPreferredSize(); final int sortWidth = vScrollBar.isVisible() ? vScrollBar.getWidth() : sortSize.width; final int sortHeight = Math.max(sortSize.height, adHeight); From b9eb9dbaeb81b0970cf307b7bc3d3ef2e1404b0a Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 17:37:49 +0200 Subject: [PATCH 064/106] cleanup --- .../com/intellij/ui/switcher/SwitchManager.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java b/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java index e3ecb9f4d4c8..df7454bc0060 100644 --- a/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java +++ b/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -77,18 +77,22 @@ public class SwitchManager implements ProjectComponent, KeyEventDispatcher, AnAc }); } + @Override public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) { if (!mySwitchActions.contains(action)) { disposeCurrentSession(false); } } + @Override public void afterActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) { } + @Override public void beforeEditorTyping(char c, DataContext dataContext) { } + @Override public boolean dispatchKeyEvent(KeyEvent e) { if (!myQa.isEnabled()) return false; @@ -112,8 +116,10 @@ public class SwitchManager implements ProjectComponent, KeyEventDispatcher, AnAc myWaitingForAutoInitSession = true; myAutoInitSessionEvent = e; Runnable initRunnable = new Runnable() { + @Override public void run() { IdeFocusManager.getInstance(myProject).doWhenFocusSettlesDown(new Runnable() { + @Override public void run() { if (myWaitingForAutoInitSession) { tryToInitSessionFromFocus(null, false); @@ -182,9 +188,11 @@ public class SwitchManager implements ProjectComponent, KeyEventDispatcher, AnAc } + @Override public void initComponent() { } + @Override public void disposeComponent() { myQa = null; } @@ -213,12 +221,15 @@ public class SwitchManager implements ProjectComponent, KeyEventDispatcher, AnAc } } + @Override public void projectOpened() { } + @Override public void projectClosed() { } + @Override @NotNull public String getComponentName() { return "ViewSwitchManager"; @@ -237,6 +248,7 @@ public class SwitchManager implements ProjectComponent, KeyEventDispatcher, AnAc public void consume(final SwitchTarget switchTarget) { mySession = null; IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new Runnable() { + @Override public void run() { tryToInitSessionFromFocus(switchTarget, showSpots).doWhenProcessed(result.createSetDoneRunnable()); } From a2828746a382756740d979b8af30cc623ab79bd0 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 18:45:08 +0200 Subject: [PATCH 065/106] SwitchManager as a service --- .../ui/switcher/QuickAccessSettings.java | 74 ++++--------- .../intellij/ui/switcher/SwitchManager.java | 104 +++--------------- .../intellij/ui/switcher/SwitchAction.java | 2 +- .../switcher/SwitchManagerAppComponent.java | 70 ++++++++++++ .../src/META-INF/PlatformExtensions.xml | 2 + .../src/componentSets/UICore.xml | 7 +- 6 files changed, 111 insertions(+), 148 deletions(-) rename platform/{platform-api => platform-impl}/src/com/intellij/ui/switcher/SwitchAction.java (98%) create mode 100644 platform/platform-impl/src/com/intellij/ui/switcher/SwitchManagerAppComponent.java diff --git a/platform/platform-api/src/com/intellij/ui/switcher/QuickAccessSettings.java b/platform/platform-api/src/com/intellij/ui/switcher/QuickAccessSettings.java index 24e980396c14..765428aacf9f 100644 --- a/platform/platform-api/src/com/intellij/ui/switcher/QuickAccessSettings.java +++ b/platform/platform-api/src/com/intellij/ui/switcher/QuickAccessSettings.java @@ -15,21 +15,18 @@ */ package com.intellij.ui.switcher; -import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.KeyboardShortcut; import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; -import com.intellij.openapi.keymap.KeymapManagerListener; -import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.registry.RegistryValue; import com.intellij.openapi.util.registry.RegistryValueListener; import com.intellij.util.containers.ContainerUtil; +import gnu.trove.THashSet; import org.intellij.lang.annotations.JdkConstants; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -37,12 +34,10 @@ import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; -import java.util.HashSet; import java.util.Set; -public class QuickAccessSettings implements ApplicationComponent, KeymapManagerListener, Disposable { - private final Set myModifierVks = new HashSet(); - private Keymap myKeymap; +public class QuickAccessSettings { + private final Set myModifierVks = new THashSet(); @NonNls public static final String SWITCH_UP = "SwitchUp"; @NonNls public static final String SWITCH_DOWN = "SwitchDown"; @NonNls public static final String SWITCH_LEFT = "SwitchLeft"; @@ -50,46 +45,20 @@ public class QuickAccessSettings implements ApplicationComponent, KeymapManagerL @NonNls public static final String SWITCH_APPLY = "SwitchApply"; private RegistryValue myModifiersValue; - @Override - @NotNull - public String getComponentName() { - return "QuickAccess"; - } - - @Override - public void initComponent() { + public QuickAccessSettings() { myModifiersValue = Registry.get("actionSystem.quickAccessModifiers"); myModifiersValue.addListener(new RegistryValueListener.Adapter() { @Override public void afterValueChanged(RegistryValue value) { applyModifiersFromRegistry(); } - }, this); - - KeymapManager kmMgr = KeymapManager.getInstance(); - kmMgr.addKeymapManagerListener(this, this); - - activeKeymapChanged(kmMgr.getActiveKeymap()); + }, ApplicationManager.getApplication()); applyModifiersFromRegistry(); } - @Override - public void disposeComponent() { - Disposer.dispose(this); - } - - @Override - public void dispose() { - } - - @Override - public void activeKeymapChanged(Keymap keymap) { - myKeymap = KeymapManager.getInstance().getActiveKeymap(); - } - Keymap getKeymap() { - return myKeymap; + return KeymapManager.getInstance().getActiveKeymap(); } void saveModifiersToRegistry(Set codeTexts) { @@ -105,13 +74,12 @@ public class QuickAccessSettings implements ApplicationComponent, KeymapManagerL private void applyModifiersFromRegistry() { Application app = ApplicationManager.getApplication(); - if (app != null && app.isUnitTestMode()) return; + if (app != null && app.isUnitTestMode()) { + return; + } - String text = getModifierRegistryValue(); - String[] vks = text.split(" "); - - HashSet vksSet = new HashSet(); - ContainerUtil.addAll(vksSet, vks); + Set vksSet = new THashSet(); + ContainerUtil.addAll(vksSet, getModifierRegistryValue().split(" ")); myModifierVks.clear(); int mask = getModifierMask(vksSet); myModifierVks.addAll(getModifiersVKs(mask)); @@ -123,30 +91,27 @@ public class QuickAccessSettings implements ApplicationComponent, KeymapManagerL reassignActionShortcut(SWITCH_APPLY, mask, KeyEvent.VK_ENTER); } + @NotNull private String getModifierRegistryValue() { String value = myModifiersValue.asString().trim(); - if (value.length() > 0) return value; - - if (SystemInfo.isMac) { - return "control alt"; - } - else { - return "shift alt"; + if (value.length() > 0) { + return value; } + return SystemInfo.isMac ? "control alt" : "shift alt"; } private void reassignActionShortcut(String actionId, @JdkConstants.InputEventMask int modifiers, int actionCode) { removeShortcuts(actionId); if (modifiers > 0) { - myKeymap.addShortcut(actionId, new KeyboardShortcut(KeyStroke.getKeyStroke(actionCode, modifiers), null)); + getKeymap().addShortcut(actionId, new KeyboardShortcut(KeyStroke.getKeyStroke(actionCode, modifiers), null)); } } private void removeShortcuts(String actionId) { - Shortcut[] shortcuts = myKeymap.getShortcuts(actionId); + Shortcut[] shortcuts = getKeymap().getShortcuts(actionId); for (Shortcut each : shortcuts) { if (each instanceof KeyboardShortcut) { - myKeymap.removeShortcut(actionId, each); + getKeymap().removeShortcut(actionId, each); } } } @@ -172,8 +137,9 @@ public class QuickAccessSettings implements ApplicationComponent, KeymapManagerL return mask; } + @NotNull public static Set getModifiersVKs(int mask) { - Set codes = new HashSet(); + Set codes = new THashSet(); if ((mask & InputEvent.SHIFT_MASK) > 0) { codes.add(KeyEvent.VK_SHIFT); } diff --git a/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java b/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java index df7454bc0060..29f88c6ba1dd 100644 --- a/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java +++ b/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java @@ -16,22 +16,15 @@ package com.intellij.ui.switcher; import com.intellij.ide.DataManager; -import com.intellij.openapi.Disposable; -import com.intellij.openapi.actionSystem.ActionManager; -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.ex.AnActionListener; -import com.intellij.openapi.components.ProjectComponent; +import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.IdeFocusManager; -import com.intellij.openapi.wm.IdeFrame; import com.intellij.util.Alarm; import com.intellij.util.Consumer; -import com.intellij.util.ui.UIUtil; +import gnu.trove.THashSet; import org.intellij.lang.annotations.JdkConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -39,12 +32,11 @@ import org.jetbrains.annotations.Nullable; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; -import java.util.HashSet; import java.util.Set; -public class SwitchManager implements ProjectComponent, KeyEventDispatcher, AnActionListener { +public class SwitchManager { private final Project myProject; - private QuickAccessSettings myQa; + private final QuickAccessSettings myQa; private SwitchingSession mySession; @@ -52,56 +44,16 @@ public class SwitchManager implements ProjectComponent, KeyEventDispatcher, AnAc private final Alarm myInitSessionAlarm = new Alarm(); private KeyEvent myAutoInitSessionEvent; - private final Set mySwitchActions = new HashSet(); + private final Set myFadingAway = new THashSet(); - private final Set myFadingAway = new HashSet(); - - public SwitchManager(Project project, QuickAccessSettings quickAccess, ActionManager actionManager) { + public SwitchManager(@NotNull Project project, QuickAccessSettings quickAccess) { myProject = project; myQa = quickAccess; - - - actionManager.addAnActionListener(this, project); - mySwitchActions.add(actionManager.getAction(QuickAccessSettings.SWITCH_UP)); - mySwitchActions.add(actionManager.getAction(QuickAccessSettings.SWITCH_DOWN)); - mySwitchActions.add(actionManager.getAction(QuickAccessSettings.SWITCH_LEFT)); - mySwitchActions.add(actionManager.getAction(QuickAccessSettings.SWITCH_RIGHT)); - mySwitchActions.add(actionManager.getAction(QuickAccessSettings.SWITCH_APPLY)); - - KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this); - Disposer.register(project, new Disposable() { - @Override - public void dispose() { - KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(SwitchManager.this); - } - }); } - @Override - public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) { - if (!mySwitchActions.contains(action)) { - disposeCurrentSession(false); - } - } - - @Override - public void afterActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) { - } - - @Override - public void beforeEditorTyping(char c, DataContext dataContext) { - } - - @Override - public boolean dispatchKeyEvent(KeyEvent e) { - if (!myQa.isEnabled()) return false; - - if (mySession != null && !mySession.isFinished()) return false; - - Component c = e.getComponent(); - Component frame = UIUtil.findUltimateParent(c); - if (frame instanceof IdeFrame) { - if (((IdeFrame)frame).getProject() != myProject) return false; + boolean dispatchKeyEvent(@NotNull KeyEvent e) { + if (isSessionActive()) { + return false; } if (e.getID() != KeyEvent.KEY_PRESSED) { @@ -136,18 +88,17 @@ public class SwitchManager implements ProjectComponent, KeyEventDispatcher, AnAc } } } - else { - if (myWaitingForAutoInitSession) { - cancelWaitingForAutoInit(); - } + else if (myWaitingForAutoInitSession) { + cancelWaitingForAutoInit(); } return false; } - private ActionCallback tryToInitSessionFromFocus(@Nullable SwitchTarget preselected, boolean showSpots) { - if (mySession != null && !mySession.isFinished()) return new ActionCallback.Rejected(); + if (isSessionActive()) { + return new ActionCallback.Rejected(); + } Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); SwitchProvider provider = SwitchProvider.KEY.getData(DataManager.getInstance().getDataContext(owner)); @@ -163,7 +114,6 @@ public class SwitchManager implements ProjectComponent, KeyEventDispatcher, AnAc myInitSessionAlarm.cancelAllRequests(); } - public static boolean areAllModifiersPressed(@JdkConstants.InputEventMask int modifiers, Set modifierCodes) { int mask = 0; for (Integer each : modifierCodes) { @@ -187,18 +137,8 @@ public class SwitchManager implements ProjectComponent, KeyEventDispatcher, AnAc return (modifiers ^ mask) == 0; } - - @Override - public void initComponent() { - } - - @Override - public void disposeComponent() { - myQa = null; - } - public static SwitchManager getInstance(Project project) { - return project != null ? project.getComponent(SwitchManager.class) : null; + return project != null ? ServiceManager.getService(project, SwitchManager.class) : null; } public SwitchingSession getSession() { @@ -221,20 +161,6 @@ public class SwitchManager implements ProjectComponent, KeyEventDispatcher, AnAc } } - @Override - public void projectOpened() { - } - - @Override - public void projectClosed() { - } - - @Override - @NotNull - public String getComponentName() { - return "ViewSwitchManager"; - } - public boolean isSessionActive() { return mySession != null && !mySession.isFinished(); } diff --git a/platform/platform-api/src/com/intellij/ui/switcher/SwitchAction.java b/platform/platform-impl/src/com/intellij/ui/switcher/SwitchAction.java similarity index 98% rename from platform/platform-api/src/com/intellij/ui/switcher/SwitchAction.java rename to platform/platform-impl/src/com/intellij/ui/switcher/SwitchAction.java index b066ee84fd99..5aa13d39c0e6 100644 --- a/platform/platform-api/src/com/intellij/ui/switcher/SwitchAction.java +++ b/platform/platform-impl/src/com/intellij/ui/switcher/SwitchAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2015 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. diff --git a/platform/platform-impl/src/com/intellij/ui/switcher/SwitchManagerAppComponent.java b/platform/platform-impl/src/com/intellij/ui/switcher/SwitchManagerAppComponent.java new file mode 100644 index 000000000000..c0cde36a766a --- /dev/null +++ b/platform/platform-impl/src/com/intellij/ui/switcher/SwitchManagerAppComponent.java @@ -0,0 +1,70 @@ +/* + * Copyright 2000-2015 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.ui.switcher; + +import com.intellij.openapi.actionSystem.ActionManager; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.actionSystem.ex.AnActionListener; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.wm.IdeFrame; +import com.intellij.util.ui.UIUtil; +import gnu.trove.THashSet; +import org.jetbrains.annotations.NotNull; + +import java.awt.*; +import java.awt.event.KeyEvent; +import java.util.Set; + +final class SwitchManagerAppComponent extends AnActionListener.Adapter implements KeyEventDispatcher { + private final Set switchActions = new THashSet(); + + public SwitchManagerAppComponent(@NotNull ActionManager actionManager) { + switchActions.add(actionManager.getAction(QuickAccessSettings.SWITCH_UP)); + switchActions.add(actionManager.getAction(QuickAccessSettings.SWITCH_DOWN)); + switchActions.add(actionManager.getAction(QuickAccessSettings.SWITCH_LEFT)); + switchActions.add(actionManager.getAction(QuickAccessSettings.SWITCH_RIGHT)); + switchActions.add(actionManager.getAction(QuickAccessSettings.SWITCH_APPLY)); + + actionManager.addAnActionListener(this); + KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this); + } + + @Override + public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) { + Project project = event.getProject(); + if (project != null && !project.isDefault() && !switchActions.contains(action)) { + SwitchManager.getInstance(project).disposeCurrentSession(false); + } + } + + @Override + public boolean dispatchKeyEvent(@NotNull KeyEvent e) { + if (!QuickAccessSettings.getInstance().isEnabled()) { + return false; + } + + Component frame = UIUtil.findUltimateParent(e.getComponent()); + if (frame instanceof IdeFrame) { + Project project = ((IdeFrame)frame).getProject(); + if (project != null && !project.isDefault()) { + return SwitchManager.getInstance(project).dispatchKeyEvent(e); + } + } + return false; + } +} diff --git a/platform/platform-resources/src/META-INF/PlatformExtensions.xml b/platform/platform-resources/src/META-INF/PlatformExtensions.xml index bdbf20ef3919..2aa9f08d34bc 100644 --- a/platform/platform-resources/src/META-INF/PlatformExtensions.xml +++ b/platform/platform-resources/src/META-INF/PlatformExtensions.xml @@ -317,6 +317,8 @@ + + diff --git a/platform/platform-resources/src/componentSets/UICore.xml b/platform/platform-resources/src/componentSets/UICore.xml index 33489e4187a6..df37933d3918 100644 --- a/platform/platform-resources/src/componentSets/UICore.xml +++ b/platform/platform-resources/src/componentSets/UICore.xml @@ -49,13 +49,12 @@ com.intellij.openapi.updateSettings.impl.UpdateCheckerComponent + + com.intellij.ui.switcher.SwitchManagerAppComponent + - - com.intellij.ui.switcher.SwitchManager - - com.intellij.ui.switcher.QuickActionManager From 776e00b899153d4f7b944dbaba7232f5eabb2c54 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 18:54:11 +0200 Subject: [PATCH 066/106] use Promise instead of ActionCallback --- .../concurrency/ConsumerRunnable.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 platform/core-api/src/org/jetbrains/concurrency/ConsumerRunnable.java diff --git a/platform/core-api/src/org/jetbrains/concurrency/ConsumerRunnable.java b/platform/core-api/src/org/jetbrains/concurrency/ConsumerRunnable.java new file mode 100644 index 000000000000..f10f67e53bf0 --- /dev/null +++ b/platform/core-api/src/org/jetbrains/concurrency/ConsumerRunnable.java @@ -0,0 +1,28 @@ +/* + * Copyright 2000-2015 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.concurrency; + +import com.intellij.util.Consumer; + +public abstract class ConsumerRunnable implements Consumer, Runnable { + @Override + public final void consume(Void aVoid) { + run(); + } + + @Override + public abstract void run(); +} From c9cd727dfcf893d720ca68e2e6e7d5c4475a4ab9 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 19:35:13 +0200 Subject: [PATCH 067/106] IDEA-142839 ActionCallback.REJECTED.doWhenProcessed results in memory leaks --- .../AttachSourcesNotificationProvider.java | 8 +-- .../InternetAttachSourceProvider.java | 6 +- .../openapi/projectRoots/ui/SdkEditor.java | 6 +- .../ui/configuration/TabbedModuleEditor.java | 17 +++++- .../BaseStructureConfigurable.java | 8 +-- .../intellij/openapi/util/ActionCallback.java | 56 ++++++++++++++++--- .../com/intellij/openapi/util/BusyObject.java | 4 +- .../openapi/util/ExecutionCallback.java | 5 +- .../execution/ui/layout/CellTransform.java | 4 +- .../ui/layout/impl/GridCellImpl.java | 4 +- .../execution/ui/layout/impl/GridImpl.java | 2 +- .../ui/layout/impl/RunnerContentUi.java | 10 ++-- .../ui/layout/impl/RunnerLayoutUiImpl.java | 4 +- .../FavoritesViewTreeBuilder.java | 4 +- .../impl/ProjectViewSelectInGroupTarget.java | 4 +- .../impl/AbstractProjectViewPSIPane.java | 4 +- .../impl/AbstractProjectViewPane.java | 4 +- .../ide/projectView/impl/ProjectViewImpl.java | 6 +- .../intellij/ide/scopeView/ScopeViewPane.java | 6 +- .../intellij/ide/todo/TodoTreeBuilder.java | 4 +- .../impl/TestEditorManagerImpl.java | 4 +- .../util/treeView/AbstractTreeBuilder.java | 10 ++-- .../ide/util/treeView/AbstractTreeUi.java | 28 +++++----- .../util/treeView/AbstractTreeUpdater.java | 4 +- .../intellij/ide/util/treeView/TreeState.java | 8 +-- .../ide/util/treeView/UpdaterTreeState.java | 4 +- .../com/intellij/openapi/wm/FocusCommand.java | 4 +- .../wm/PassThroughIdeFocusManager.java | 6 +- .../ui/AutoScrollToSourceHandler.java | 2 +- .../src/com/intellij/ui/navigation/Place.java | 6 +- .../intellij/ui/switcher/SwitchManager.java | 6 +- .../com/intellij/ui/tabs/impl/JBTabsImpl.java | 10 ++-- .../com/intellij/util/ui/tree/TreeUtil.java | 18 +++--- .../com/intellij/ide/impl/ProjectUtil.java | 2 +- .../actionSystem/impl/ActionToolbarImpl.java | 2 +- .../impl/EditorTabbedContainer.java | 4 +- .../intellij/openapi/options/ex/Settings.java | 4 +- .../options/newEditor/IdeSettingsDialog.java | 8 +-- .../options/newEditor/OptionsEditor.java | 10 ++-- .../newEditor/OptionsEditorColleague.java | 12 ++-- .../newEditor/OptionsEditorContext.java | 12 ++-- .../newEditor/OptionsEditorDialog.java | 8 +-- .../options/newEditor/OptionsTree.java | 10 ++-- .../options/newEditor/SettingsFilter.java | 4 +- .../options/newEditor/SettingsTreeView.java | 10 ++-- .../ui/impl/GlassPaneDialogWrapperPeer.java | 2 +- .../ui/playback/commands/AbstractCommand.java | 4 +- .../ui/playback/commands/ActionCommand.java | 2 +- .../ui/playback/commands/CallCommand.java | 12 ++-- .../ui/playback/commands/CdCommand.java | 6 +- .../ui/playback/commands/DelayCommand.java | 6 +- .../ui/playback/commands/EmptyCommand.java | 4 +- .../ui/playback/commands/ErrorCommand.java | 4 +- .../playback/commands/KeyShortcutCommand.java | 6 +- .../ui/playback/commands/PopStage.java | 4 +- .../ui/playback/commands/PrintCommand.java | 4 +- .../ui/playback/commands/PushStage.java | 4 +- .../commands/RegistryValueCommand.java | 6 +- .../ui/playback/commands/StopCommand.java | 4 +- .../commands/ToggleActionCommand.java | 10 ++-- .../openapi/wm/impl/FocusManagerImpl.java | 8 +-- .../wm/impl/IdeFocusManagerHeadless.java | 8 +-- .../impl/ToolWindowHeadlessManagerImpl.java | 18 +++--- .../openapi/wm/impl/ToolWindowImpl.java | 4 +- .../wm/impl/ToolWindowManagerImpl.java | 12 ++-- .../commands/RequestFocusInToolWindowCmd.java | 4 +- .../src/com/intellij/ui/BalloonImpl.java | 2 +- .../src/com/intellij/ui/FocusTrackback.java | 4 +- .../ui/content/impl/ContentManagerImpl.java | 20 +++---- .../com/intellij/ui/popup/AbstractPopup.java | 8 +-- .../util/treeView/AbstractTreeStructure.java | 8 +-- .../src/com/intellij/mock/Mock.java | 11 ++-- .../utils/MavenAttachSourcesProvider.java | 8 ++- 73 files changed, 308 insertions(+), 247 deletions(-) diff --git a/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java b/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java index 74360a3b61f8..23a85aa41e57 100644 --- a/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java +++ b/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java @@ -254,7 +254,7 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi model.addRoot(root, OrderRootType.SOURCES); modelsToCommit.add(model); } - if (modelsToCommit.isEmpty()) return new ActionCallback.Rejected(); + if (modelsToCommit.isEmpty()) return ActionCallback.REJECTED; new WriteAction() { @Override protected void run(@NotNull final Result result) { @@ -264,7 +264,7 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi } }.execute(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Nullable @@ -307,7 +307,7 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi VirtualFile[] candidates = FileChooser.chooseFiles(descriptor, myProject, roots.length == 0 ? null : PathUtil.getLocalFile(roots[0])); final VirtualFile[] files = PathUIUtils.scanAndSelectDetectedJavaSourceRoots(myParentComponent, candidates); if (files.length == 0) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } final Map librariesToAppendSourcesTo = new HashMap(); @@ -350,7 +350,7 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi }).showCenteredInCurrentWindow(myProject); } - return new ActionCallback.Done(); + return ActionCallback.DONE; } private static void appendSources(final Library library, final VirtualFile[] files) { diff --git a/java/idea-ui/src/com/intellij/jarFinder/InternetAttachSourceProvider.java b/java/idea-ui/src/com/intellij/jarFinder/InternetAttachSourceProvider.java index be42dd7fbf8b..8ee9e96245c0 100644 --- a/java/idea-ui/src/com/intellij/jarFinder/InternetAttachSourceProvider.java +++ b/java/idea-ui/src/com/intellij/jarFinder/InternetAttachSourceProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -119,7 +119,7 @@ public class InternetAttachSourceProvider implements AttachSourcesProvider { @Override public ActionCallback perform(List orderEntriesContainingFile) { attachSourceJar(sourceFile, libraries); - return new ActionCallback.Done(); + return ActionCallback.DONE; } }); } @@ -191,7 +191,7 @@ public class InternetAttachSourceProvider implements AttachSourcesProvider { task.queue(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } }); } diff --git a/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java b/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java index ae544ea419ed..ce4a91952281 100644 --- a/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java +++ b/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/SdkEditor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -477,9 +477,9 @@ public class SdkEditor implements Configurable, Place.Navigator { @Override public ActionCallback navigateTo(@Nullable final Place place, final boolean requestFocus) { - if (place == null) return new ActionCallback.Done(); + if (place == null) return ActionCallback.DONE; myTabbedPane.setSelectedTitle((String)place.getPath(SDK_TAB)); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/TabbedModuleEditor.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/TabbedModuleEditor.java index 2763b597787d..b9612d69307e 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/TabbedModuleEditor.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/TabbedModuleEditor.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2015 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.roots.ui.configuration; import com.intellij.ide.util.PropertiesComponent; @@ -70,7 +85,7 @@ public abstract class TabbedModuleEditor extends ModuleEditor { if (place != null) { selectEditor((String)place.getPath(SELECTED_EDITOR_NAME)); } - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java index a3b1db0dcf24..a0d32a3f4e11 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseStructureConfigurable.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -98,17 +98,17 @@ public abstract class BaseStructureConfigurable extends MasterDetailsComponent i @Override public ActionCallback navigateTo(@Nullable final Place place, final boolean requestFocus) { - if (place == null) return new ActionCallback.Done(); + if (place == null) return ActionCallback.DONE; final Object object = place.getPath(TREE_OBJECT); final String byName = (String)place.getPath(TREE_NAME); - if (object == null && byName == null) return new ActionCallback.Done(); + if (object == null && byName == null) return ActionCallback.DONE; final MyNode node = object == null ? null : findNodeByObject(myRoot, object); final MyNode nodeByName = byName == null ? null : findNodeByName(myRoot, byName); - if (node == null && nodeByName == null) return new ActionCallback.Done(); + if (node == null && nodeByName == null) return ActionCallback.DONE; final NamedConfigurable config; if (node != null) { diff --git a/platform/core-api/src/com/intellij/openapi/util/ActionCallback.java b/platform/core-api/src/com/intellij/openapi/util/ActionCallback.java index cc3810d90bb6..85e2a57adca4 100644 --- a/platform/core-api/src/com/intellij/openapi/util/ActionCallback.java +++ b/platform/core-api/src/com/intellij/openapi/util/ActionCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -46,6 +46,12 @@ public class ActionCallback implements Disposable { myRejected = new ExecutionCallback(); } + private ActionCallback(ExecutionCallback done, ExecutionCallback rejected) { + myDone = done; + myRejected = rejected; + myName = null; + } + public ActionCallback(int countToDone) { this(null, countToDone); } @@ -54,10 +60,7 @@ public class ActionCallback implements Disposable { myName = name; assert countToDone >= 0 : "count=" + countToDone; - - int count = countToDone >= 1 ? countToDone : 1; - - myDone = new ExecutionCallback(count); + myDone = new ExecutionCallback(countToDone >= 1 ? countToDone : 1); myRejected = new ExecutionCallback(); if (countToDone < 1) { @@ -164,13 +167,52 @@ public class ActionCallback implements Disposable { public static class Done extends ActionCallback { public Done() { - setDone(); + super(new ExecutedExecutionCallback(), new IgnoreExecutionCallback()); } } public static class Rejected extends ActionCallback { public Rejected() { - setRejected(); + super(new IgnoreExecutionCallback(), new ExecutedExecutionCallback()); + } + } + + private static class ExecutedExecutionCallback extends ExecutionCallback { + public ExecutedExecutionCallback() { + super(0); + } + + @Override + void doWhenExecuted(@NotNull Runnable runnable) { + runnable.run(); + } + + @Override + boolean setExecuted() { + throw new IllegalStateException("Forbidden"); + } + + @SuppressWarnings("NonSynchronizedMethodOverridesSynchronizedMethod") + @Override + boolean isExecuted() { + return true; + } + } + + private static class IgnoreExecutionCallback extends ExecutionCallback { + @Override + void doWhenExecuted(@NotNull Runnable runnable) { + } + + @Override + boolean setExecuted() { + throw new IllegalStateException("Forbidden"); + } + + @SuppressWarnings("NonSynchronizedMethodOverridesSynchronizedMethod") + @Override + boolean isExecuted() { + return false; } } diff --git a/platform/core-api/src/com/intellij/openapi/util/BusyObject.java b/platform/core-api/src/com/intellij/openapi/util/BusyObject.java index 915bc15d7224..7bc3f69a2360 100644 --- a/platform/core-api/src/com/intellij/openapi/util/BusyObject.java +++ b/platform/core-api/src/com/intellij/openapi/util/BusyObject.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -65,7 +65,7 @@ public interface BusyObject { @NotNull public final ActionCallback getReady(@NotNull Object requestor) { if (isReady()) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } return addReadyCallback(requestor); } diff --git a/platform/core-api/src/com/intellij/openapi/util/ExecutionCallback.java b/platform/core-api/src/com/intellij/openapi/util/ExecutionCallback.java index 5c72eb06def3..03912c25763f 100644 --- a/platform/core-api/src/com/intellij/openapi/util/ExecutionCallback.java +++ b/platform/core-api/src/com/intellij/openapi/util/ExecutionCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -34,7 +34,6 @@ class ExecutionCallback { ExecutionCallback(int executedCount) { myCountToExecution = executedCount; - assert executedCount >= 1 : executedCount; } /** @@ -74,7 +73,7 @@ class ExecutionCallback { } } - final void doWhenExecuted(@NotNull final Runnable runnable) { + void doWhenExecuted(@NotNull final Runnable runnable) { Runnable toRun; synchronized (this) { if (isExecuted()) { diff --git a/platform/lang-api/src/com/intellij/execution/ui/layout/CellTransform.java b/platform/lang-api/src/com/intellij/execution/ui/layout/CellTransform.java index 6ca574195417..1012a3380b0d 100644 --- a/platform/lang-api/src/com/intellij/execution/ui/layout/CellTransform.java +++ b/platform/lang-api/src/com/intellij/execution/ui/layout/CellTransform.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -37,7 +37,7 @@ public interface CellTransform { @Override public ActionCallback restoreInGrid() { myRestoringNow = true; - if (myActions.size() == 0) return new ActionCallback.Done(); + if (myActions.size() == 0) return ActionCallback.DONE; final ActionCallback topCallback = restore(0); return topCallback.doWhenDone(new Runnable() { @Override diff --git a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridCellImpl.java b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridCellImpl.java index dea14877f2eb..e380cc918be5 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridCellImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridCellImpl.java @@ -282,7 +282,7 @@ public class GridCellImpl implements GridCell { public ActionCallback select(final Content content, final boolean requestFocus) { final TabInfo tabInfo = myContents.getValue(content); - return tabInfo != null ? myTabs.select(tabInfo, requestFocus) : new ActionCallback.Done(); + return tabInfo != null ? myTabs.select(tabInfo, requestFocus) : ActionCallback.DONE; } public void processAlert(final Content content, final boolean activate) { @@ -511,6 +511,6 @@ public class GridCellImpl implements GridCell { ActionCallback restore(Content content) { myMinimizedContents.remove(content); - return new ActionCallback.Done(); + return ActionCallback.DONE; } } diff --git a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridImpl.java b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridImpl.java index 323bf25cd436..be7cf867b1fe 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridImpl.java @@ -245,7 +245,7 @@ public class GridImpl extends Wrapper implements Grid, Disposable, DataProvider setContent(myContent); myContent = null; } - return new ActionCallback.Done(); + return ActionCallback.DONE; } }; } diff --git a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerContentUi.java b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerContentUi.java index 36f02aa88577..b94f49eff259 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerContentUi.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerContentUi.java @@ -433,7 +433,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac location.translate(size.width / 2, size.height / 2); getDockManager().createNewDockContainerFor(content, new RelativePoint(location)); } - return new ActionCallback.Done(); + return ActionCallback.DONE; } private void storeDefaultIndices(@NotNull Content[] contents) { @@ -971,7 +971,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac } private ActionCallback restoreLastUiState() { - if (isStateBeingRestored()) return new ActionCallback.Rejected(); + if (isStateBeingRestored()) return ActionCallback.REJECTED; try { setStateIsBeingRestored(true, this); @@ -1569,7 +1569,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac saveUiState(); select(content, true); updateTabsUI(false); - return new ActionCallback.Done(); + return ActionCallback.DONE; } })); @@ -1617,11 +1617,11 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac @Override public ActionCallback select(final Content content, final boolean requestFocus) { final GridImpl grid = (GridImpl)findGridFor(content); - if (grid == null) return new ActionCallback.Done(); + if (grid == null) return ActionCallback.DONE; final TabInfo info = myTabs.findInfo(grid); - if (info == null) return new ActionCallback.Done(); + if (info == null) return ActionCallback.DONE; final ActionCallback result = new ActionCallback(); diff --git a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerLayoutUiImpl.java b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerLayoutUiImpl.java index 7475adbcab21..746cd1aa0189 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerLayoutUiImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/RunnerLayoutUiImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -191,7 +191,7 @@ public class RunnerLayoutUiImpl implements Disposable.Parent, RunnerLayoutUi, La @NotNull @Override public ActionCallback selectAndFocus(@Nullable final Content content, boolean requestFocus, final boolean forced, boolean implicit) { - if (content == null) return new ActionCallback.Rejected(); + if (content == null) return ActionCallback.REJECTED; return getContentManager(content).setSelectedContent(content, requestFocus || shouldRequestFocus(), forced, implicit); } diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesViewTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesViewTreeBuilder.java index 32cf92c011dc..729b3d1d079d 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesViewTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesViewTreeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -143,7 +143,7 @@ public class FavoritesViewTreeBuilder extends BaseProjectTreeBuilder { @NotNull public ActionCallback updateFromRootCB() { getStructure().rootsChanged(); - if (isDisposed()) return new ActionCallback.Done(); + if (isDisposed()) return ActionCallback.DONE; getUpdater().cancelAllRequests(); return super.updateFromRootCB(); } diff --git a/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInGroupTarget.java b/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInGroupTarget.java index a0fb4f5d389d..62ebf41fb4e4 100644 --- a/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInGroupTarget.java +++ b/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInGroupTarget.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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,7 +72,7 @@ public class ProjectViewSelectInGroupTarget implements CompositeSelectInTarget, @Override public ActionCallback run() { target.selectIn(context, requestFocus); - return new ActionCallback.Done(); + return ActionCallback.DONE; } }, true); } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java index 593d2576f370..d8d666d7e3ef 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPSIPane.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -196,7 +196,7 @@ public abstract class AbstractProjectViewPSIPane extends AbstractProjectViewPane if (file != null) { return ((BaseProjectTreeBuilder)getTreeBuilder()).select(element, file, requestFocus); } - return new ActionCallback.Done(); + return ActionCallback.DONE; } @NotNull diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java index 9fd369978507..0ba8d9e193bf 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/AbstractProjectViewPane.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -706,7 +706,7 @@ public abstract class AbstractProjectViewPane implements DataProvider, Disposabl @NotNull @Override public ActionCallback getReady(@NotNull Object requestor) { - if (myTreeBuilder == null || myTreeBuilder.isDisposed()) return new ActionCallback.Rejected(); + if (myTreeBuilder == null || myTreeBuilder.isDisposed()) return ActionCallback.REJECTED; return myTreeBuilder.getUi().getReady(requestor); } } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java index 5085a0487cdb..94a0db1b58f7 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewImpl.java @@ -783,7 +783,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo return ((AbstractProjectViewPSIPane)viewPane).selectCB(element, file, requestFocus); } select(element, file, requestFocus); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -1535,7 +1535,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo return pane.updateFromRoot(false); } } - return new ActionCallback.Done(); + return ActionCallback.DONE; } private static boolean getPaneOptionValue(@NotNull Map optionsMap, String paneId, boolean defaultValue) { @@ -1906,6 +1906,6 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo if (pane == null) { pane = myId2Pane.get(myCurrentViewId); } - return pane != null ? pane.getReady(requestor) : new ActionCallback.Done(); + return pane != null ? pane.getReady(requestor) : ActionCallback.DONE; } } diff --git a/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeViewPane.java b/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeViewPane.java index 183ada37ec94..63958fb514a0 100644 --- a/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeViewPane.java +++ b/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeViewPane.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -190,7 +190,7 @@ public class ScopeViewPane extends AbstractProjectViewPane { saveExpandedPaths(); myViewPanel.selectScope(NamedScopesHolder.getScope(myProject, getSubId())); restoreExpandedPaths(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -271,6 +271,6 @@ public class ScopeViewPane extends AbstractProjectViewPane { @Override public ActionCallback getReady(@NotNull Object requestor) { final ActionCallback callback = myViewPanel.getActionCallback(); - return callback == null ? new ActionCallback.Done() : callback; + return callback == null ? ActionCallback.DONE : callback; } } diff --git a/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java index 5f52f5ddfdf6..9f6129dee7a0 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -203,7 +203,7 @@ public abstract class TodoTreeBuilder extends AbstractTreeBuilder { return callback; } - return new ActionCallback.Done(); + return ActionCallback.DONE; } }; } diff --git a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/TestEditorManagerImpl.java b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/TestEditorManagerImpl.java index 2234f72cdb97..ae711786dbe4 100644 --- a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/TestEditorManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/TestEditorManagerImpl.java @@ -113,7 +113,7 @@ public class TestEditorManagerImpl extends FileEditorManagerEx implements Projec @Override public ActionCallback notifyPublisher(@NotNull Runnable runnable) { runnable.run(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -494,7 +494,7 @@ public class TestEditorManagerImpl extends FileEditorManagerEx implements Projec @NotNull @Override public ActionCallback getReady(@NotNull Object requestor) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java index f57a44485e69..21b2c64821b5 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeBuilder.java @@ -298,7 +298,7 @@ public class AbstractTreeBuilder implements Disposable { @NotNull public ActionCallback queueUpdateFrom(final Object element, final boolean forceResort, final boolean updateStructure) { - if (getUi() == null) return new ActionCallback.Rejected(); + if (getUi() == null) return ActionCallback.REJECTED; final ActionCallback result = new ActionCallback(); @@ -487,14 +487,14 @@ public class AbstractTreeBuilder implements Disposable { @NotNull public final ActionCallback getInitialized() { if (isDisposed()) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } return myUi.getInitialized(); } @NotNull public final ActionCallback getReady(Object requestor) { - if (isDisposed()) return new ActionCallback.Rejected(); + if (isDisposed()) return ActionCallback.REJECTED; return myUi.getReady(requestor); } @@ -517,14 +517,14 @@ public class AbstractTreeBuilder implements Disposable { @NotNull public ActionCallback cancelUpdate() { - if (isDisposed()) return new ActionCallback.Rejected(); + if (isDisposed()) return ActionCallback.REJECTED; return getUi().cancelUpdate(); } @NotNull public ActionCallback batch(@NotNull Progressive progressive) { - if (isDisposed()) return new ActionCallback.Rejected(); + if (isDisposed()) return ActionCallback.REJECTED; return getUi().batch(progressive); } diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java index ee52b27807ad..07f2d7f6629e 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUi.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -736,7 +736,7 @@ public class AbstractTreeUi { } ActionCallback callback; if (willUpdate) { - callback = new ActionCallback.Done(); + callback = ActionCallback.DONE; } else { callback = updateNodeChildren(getRootNode(), pass, null, false, false, false, true, true); @@ -1006,7 +1006,7 @@ public class AbstractTreeUi { try { AbstractTreeUpdater updater = getUpdater(); if (updater == null) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } final ActionCallback result = new ActionCallback(); @@ -1034,7 +1034,7 @@ public class AbstractTreeUi { return result; } catch (ProcessCanceledException e) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } } @@ -1567,7 +1567,7 @@ public class AbstractTreeUi { @Override public ActionCallback run() { expand(element, null); - return new ActionCallback.Done(); + return ActionCallback.DONE; } }, pass, node); } @@ -1695,8 +1695,8 @@ public class AbstractTreeUi { @NotNull @Override public ActionCallback run() { - if (pass.isExpired()) return new ActionCallback.Rejected(); - if (childNodes.isEmpty()) return new ActionCallback.Done(); + if (pass.isExpired()) return ActionCallback.REJECTED; + if (childNodes.isEmpty()) return ActionCallback.DONE; final ActionCallback result = new ActionCallback(childNodes.size()); @@ -1885,7 +1885,7 @@ public class AbstractTreeUi { @NotNull private ActionCallback resetToReadyNow() { - if (isReleased()) return new ActionCallback.Rejected(); + if (isReleased()) return ActionCallback.REJECTED; assertIsDispatchThread(); @@ -2408,7 +2408,7 @@ public class AbstractTreeUi { @NotNull public ActionCallback cancelUpdate() { - if (isReleased()) return new ActionCallback.Rejected(); + if (isReleased()) return ActionCallback.REJECTED; setCancelRequested(true); @@ -2503,7 +2503,7 @@ public class AbstractTreeUi { return callback; } finally { - if (isReleased()) return new ActionCallback.Rejected(); + if (isReleased()) return ActionCallback.REJECTED; _getReady().doWhenDone(new TreeRunnable("AbstractTreeUi.batch: finally") { @Override @@ -2991,17 +2991,17 @@ public class AbstractTreeUi { final boolean forceUpdate, @Nullable LoadedChildren parentPreloadedChildren) { if (pass.isExpired()) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } if (childDescriptor == null) { pass.expire(); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } final Object oldElement = getElementFromDescriptor(childDescriptor); if (oldElement == null) { pass.expire(); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } AsyncResult update = new AsyncResult(); @@ -3347,7 +3347,7 @@ public class AbstractTreeUi { @NotNull private ActionCallback queueToBackground(@NotNull final Runnable bgBuildAction, @Nullable final Runnable edtPostRunnable) { - if (!canInitiateNewActivity()) return new ActionCallback.Rejected(); + if (!canInitiateNewActivity()) return ActionCallback.REJECTED; final ActionCallback result = new ActionCallback(); final AtomicBoolean fail = new AtomicBoolean(); final Runnable finalizer = new TreeRunnable("AbstractTreeUi.queueToBackground: finalizer") { diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java index fcf37784ba4b..3d07e15d4dfd 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -299,7 +299,7 @@ public class AbstractTreeUpdater implements Disposable, Activatable { } protected ActionCallback beforeUpdate(TreeUpdatePass pass) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } /** diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/TreeState.java b/platform/platform-api/src/com/intellij/ide/util/treeView/TreeState.java index 6b2101ff23dd..1411eaa4439e 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/TreeState.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/TreeState.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -437,7 +437,7 @@ public class TreeState implements JDOMExternalizable { @Override public ActionCallback expand(DefaultMutableTreeNode node) { myTree.expandPath(new TreePath(node.getPath())); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -445,7 +445,7 @@ public class TreeState implements JDOMExternalizable { final WeakReference ref = (WeakReference)myTree.getClientProperty(CALLBACK); final ActionCallback callback = SoftReference.dereference(ref); if (callback != null) return callback; - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -475,7 +475,7 @@ public class TreeState implements JDOMExternalizable { @Override public ActionCallback expand(DefaultMutableTreeNode node) { final Object userObject = node.getUserObject(); - if (!(userObject instanceof NodeDescriptor)) return new ActionCallback.Rejected(); + if (!(userObject instanceof NodeDescriptor)) return ActionCallback.REJECTED; NodeDescriptor desc = (NodeDescriptor)userObject; diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/UpdaterTreeState.java b/platform/platform-api/src/com/intellij/ide/util/treeView/UpdaterTreeState.java index 783bd87f8d52..4e47eb39ef5b 100644 --- a/platform/platform-api/src/com/intellij/ide/util/treeView/UpdaterTreeState.java +++ b/platform/platform-api/src/com/intellij/ide/util/treeView/UpdaterTreeState.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -299,7 +299,7 @@ public class UpdaterTreeState { } private ActionCallback processHangByParent(Set elements) { - if (elements.isEmpty()) return new ActionCallback.Done(); + if (elements.isEmpty()) return ActionCallback.DONE; ActionCallback result = new ActionCallback(elements.size()); for (Object hangElement : elements) { diff --git a/platform/platform-api/src/com/intellij/openapi/wm/FocusCommand.java b/platform/platform-api/src/com/intellij/openapi/wm/FocusCommand.java index 837dc540629d..304a534826df 100644 --- a/platform/platform-api/src/com/intellij/openapi/wm/FocusCommand.java +++ b/platform/platform-api/src/com/intellij/openapi/wm/FocusCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -212,7 +212,7 @@ public abstract class FocusCommand extends ActiveRunnable implements Expirable { } clear(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } private void clear() { diff --git a/platform/platform-api/src/com/intellij/openapi/wm/PassThroughIdeFocusManager.java b/platform/platform-api/src/com/intellij/openapi/wm/PassThroughIdeFocusManager.java index e7bcf55b81b3..f124c85a9f5a 100644 --- a/platform/platform-api/src/com/intellij/openapi/wm/PassThroughIdeFocusManager.java +++ b/platform/platform-api/src/com/intellij/openapi/wm/PassThroughIdeFocusManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -36,7 +36,7 @@ public class PassThroughIdeFocusManager extends IdeFocusManager { @NotNull public ActionCallback requestFocus(@NotNull Component c, boolean forced) { c.requestFocus(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @NotNull @@ -78,7 +78,7 @@ public class PassThroughIdeFocusManager extends IdeFocusManager { @NotNull public ActionCallback requestDefaultFocus(boolean forced) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/platform/platform-api/src/com/intellij/ui/AutoScrollToSourceHandler.java b/platform/platform-api/src/com/intellij/ui/AutoScrollToSourceHandler.java index d69c9cab72c8..0259031eb7c2 100644 --- a/platform/platform-api/src/com/intellij/ui/AutoScrollToSourceHandler.java +++ b/platform/platform-api/src/com/intellij/ui/AutoScrollToSourceHandler.java @@ -232,7 +232,7 @@ public abstract class AutoScrollToSourceHandler { private ActionCallback getReady(DataContext context) { ToolWindow toolWindow = PlatformDataKeys.TOOL_WINDOW.getData(context); - return toolWindow != null ? toolWindow.getReady(this) : new ActionCallback.Done(); + return toolWindow != null ? toolWindow.getReady(this) : ActionCallback.DONE; } } diff --git a/platform/platform-api/src/com/intellij/ui/navigation/Place.java b/platform/platform-api/src/com/intellij/ui/navigation/Place.java index 7cbd68572bd8..2dfe580f0f8e 100644 --- a/platform/platform-api/src/com/intellij/ui/navigation/Place.java +++ b/platform/platform-api/src/com/intellij/ui/navigation/Place.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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,8 +22,8 @@ import com.intellij.util.ui.update.ComparableObjectCheck; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.LinkedHashMap; import java.util.Iterator; +import java.util.LinkedHashMap; public class Place implements ComparableObject { @@ -105,7 +105,7 @@ public class Place implements ComparableObject { if (object instanceof Navigator) { return ((Navigator)object).navigateTo(place, requestFocus); } - return new ActionCallback.Done(); + return ActionCallback.DONE; } public static void queryFurther(final Object object, final Place place) { diff --git a/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java b/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java index 29f88c6ba1dd..af2b4d529966 100644 --- a/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java +++ b/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java @@ -97,7 +97,7 @@ public class SwitchManager { private ActionCallback tryToInitSessionFromFocus(@Nullable SwitchTarget preselected, boolean showSpots) { if (isSessionActive()) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); @@ -106,7 +106,7 @@ public class SwitchManager { return initSession(new SwitchingSession(this, provider, myAutoInitSessionEvent, preselected, showSpots)); } - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } private void cancelWaitingForAutoInit() { @@ -150,7 +150,7 @@ public class SwitchManager { disposeCurrentSession(false); mySession = session; - return new ActionCallback.Done(); + return ActionCallback.DONE; } public void disposeCurrentSession(boolean fadeAway) { diff --git a/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java b/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java index beab46c97e22..818e5db836b4 100644 --- a/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java +++ b/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java @@ -884,14 +884,14 @@ public class JBTabsImpl extends JComponent private ActionCallback executeSelectionChange(TabInfo info, boolean requestFocus) { if (mySelectedInfo != null && mySelectedInfo.equals(info)) { if (!requestFocus) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } else { Component owner = myFocusManager.getFocusOwner(); JComponent c = info.getComponent(); if (c != null && owner != null) { if (c == owner || SwingUtilities.isDescendingFrom(owner, c)) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } } return requestFocus(getToFocus()); @@ -984,11 +984,11 @@ public class JBTabsImpl extends JComponent @NotNull private ActionCallback requestFocus(final JComponent toFocus) { - if (toFocus == null) return new ActionCallback.Done(); + if (toFocus == null) return ActionCallback.DONE; if (myTestMode) { toFocus.requestFocus(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @@ -2533,7 +2533,7 @@ public class JBTabsImpl extends JComponent @NotNull private ActionCallback removeTab(TabInfo info, @Nullable TabInfo forcedSelectionTransfer, boolean transferFocus, boolean isDropTarget) { if (!isDropTarget) { - if (info == null || !getTabs().contains(info)) return new ActionCallback.Done(); + if (info == null || !getTabs().contains(info)) return ActionCallback.DONE; } if (isDropTarget && myLastLayoutPass != null) { diff --git a/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java b/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java index 9443bb559f96..0d947d45c440 100644 --- a/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java +++ b/platform/platform-api/src/com/intellij/util/ui/tree/TreeUtil.java @@ -395,7 +395,7 @@ public final class TreeUtil { row++; return showAndSelect(tree, row, row + 2, row, getSelectedRow(tree), false, true, true); } else { - return new ActionCallback.Done(); + return ActionCallback.DONE; } } @@ -406,7 +406,7 @@ public final class TreeUtil { row--; return showAndSelect(tree, row - 2, row, row, getSelectedRow(tree), false, true, true); } else { - return new ActionCallback.Done(); + return ActionCallback.DONE; } } @@ -485,12 +485,12 @@ public final class TreeUtil { public static ActionCallback showAndSelect(@NotNull final JTree tree, int top, int bottom, final int row, final int previous, final boolean addToSelection, final boolean scroll, final boolean resetSelection) { final TreePath path = tree.getPathForRow(row); - if (path == null) return new ActionCallback.Done(); + if (path == null) return ActionCallback.DONE; final int size = tree.getRowCount(); if (size == 0) { tree.clearSelection(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } if (top < 0){ top = 0; @@ -499,7 +499,7 @@ public final class TreeUtil { bottom = size - 1; } - if (row >= tree.getRowCount()) return new ActionCallback.Done(); + if (row >= tree.getRowCount()) return ActionCallback.DONE; boolean okToScroll = true; if (tree.isShowing()) { @@ -533,12 +533,12 @@ public final class TreeUtil { if (!okToScroll) { selectRunnable.run(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } final Rectangle rowBounds = tree.getRowBounds(row); - if (rowBounds == null) return new ActionCallback.Done(); + if (rowBounds == null) return ActionCallback.DONE; Rectangle topBounds = tree.getRowBounds(top); if (topBounds == null) { @@ -835,7 +835,7 @@ public final class TreeUtil { @NotNull public static ActionCallback selectInTree(@Nullable DefaultMutableTreeNode node, boolean requestFocus, @NotNull JTree tree, boolean center) { - if (node == null) return new ActionCallback.Done(); + if (node == null) return ActionCallback.DONE; final TreePath treePath = new TreePath(node.getPath()); tree.expandPath(treePath); @@ -847,7 +847,7 @@ public final class TreeUtil { @NotNull public static ActionCallback selectInTree(Project project, @Nullable DefaultMutableTreeNode node, boolean requestFocus, @NotNull JTree tree, boolean center) { - if (node == null) return new ActionCallback.Done(); + if (node == null) return ActionCallback.DONE; final TreePath treePath = new TreePath(node.getPath()); tree.expandPath(treePath); diff --git a/platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.java b/platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.java index 79da05f596cb..111a9323cad6 100644 --- a/platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.java +++ b/platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.java @@ -263,7 +263,7 @@ public class ProjectUtil { f.toFront(); //f.requestFocus(); } - return new ActionCallback.Done(); + return ActionCallback.DONE; } }; diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java index 4dfa9f7a8ee7..319ce8916256 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java @@ -1258,7 +1258,7 @@ public class ActionToolbarImpl extends JPanel implements ActionToolbar { @Override public ActionCallback switchTo(boolean requestFocus) { myButton.click(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorTabbedContainer.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorTabbedContainer.java index eb3b31817269..3835787456b2 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorTabbedContainer.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorTabbedContainer.java @@ -183,7 +183,7 @@ public final class EditorTabbedContainer implements Disposable, CloseAction.Clos } public ActionCallback setSelectedIndex(final int indexToSelect, boolean focusEditor) { - if (indexToSelect >= myTabs.getTabCount()) return new ActionCallback.Rejected(); + if (indexToSelect >= myTabs.getTabCount()) return ActionCallback.REJECTED; return myTabs.select(myTabs.getTabAt(indexToSelect), focusEditor); } @@ -252,7 +252,7 @@ public final class EditorTabbedContainer implements Disposable, CloseAction.Clos toSelect = null; } final ActionCallback callback = myTabs.removeTab(info, toSelect, transferFocus); - return myProject.isOpen() ? callback : new ActionCallback.Done(); + return myProject.isOpen() ? callback : ActionCallback.DONE; } public ActionCallback removeTabAt(final int componentIndex, int indexToSelect) { diff --git a/platform/platform-impl/src/com/intellij/openapi/options/ex/Settings.java b/platform/platform-impl/src/com/intellij/openapi/options/ex/Settings.java index a352c621af4c..0b27b1144952 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/ex/Settings.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/ex/Settings.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -53,7 +53,7 @@ public abstract class Settings { public final ActionCallback select(Configurable configurable) { return configurable != null ? selectImpl(choose(configurable, myMap.get(configurable))) - : new ActionCallback.Rejected(); + : ActionCallback.REJECTED; } protected abstract ActionCallback selectImpl(Configurable configurable); diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/IdeSettingsDialog.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/IdeSettingsDialog.java index 5c720c413e00..68e67037b690 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/IdeSettingsDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/IdeSettingsDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -138,19 +138,19 @@ public class IdeSettingsDialog extends DialogWrapper implements DataProvider { @Override public ActionCallback onModifiedAdded(final Configurable configurable) { updateStatus(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override public ActionCallback onModifiedRemoved(final Configurable configurable) { updateStatus(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override public ActionCallback onErrorsChanged() { updateStatus(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } }); Disposer.register(myDisposable, myEditor); diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditor.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditor.java index d1ebb4063e1d..723953d1aca3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditor.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditor.java @@ -324,7 +324,7 @@ public class OptionsEditor extends JPanel implements DataProvider, Place.Navigat public ActionCallback select(Class configurableClass) { final Configurable configurable = findConfigurable(configurableClass); if (configurable == null) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } return select(configurable); } @@ -379,7 +379,7 @@ public class OptionsEditor extends JPanel implements DataProvider, Place.Navigat } private ActionCallback processSelected(final Configurable configurable, final Configurable oldConfigurable) { - if (isShowing(configurable)) return new ActionCallback.Done(); + if (isShowing(configurable)) return ActionCallback.DONE; final ActionCallback result = new ActionCallback(); @@ -452,7 +452,7 @@ public class OptionsEditor extends JPanel implements DataProvider, Place.Navigat assertIsDispatchThread(); if (myDisposed) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } final ActionCallback result = new ActionCallback(); @@ -931,9 +931,9 @@ public class OptionsEditor extends JPanel implements DataProvider, Place.Navigat updateDetails(); final ConfigurableContent content = myConfigurable2Content.get(configurable); content.updateBannerActions(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } else { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } } } diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorColleague.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorColleague.java index 62d473762002..9df60fc0f148 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorColleague.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorColleague.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -15,9 +15,9 @@ */ package com.intellij.openapi.options.newEditor; -import org.jetbrains.annotations.Nullable; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.util.ActionCallback; +import org.jetbrains.annotations.Nullable; interface OptionsEditorColleague { ActionCallback onSelected(@Nullable Configurable configurable, final Configurable oldConfigurable); @@ -30,19 +30,19 @@ interface OptionsEditorColleague { class Adapter implements OptionsEditorColleague { public ActionCallback onSelected(@Nullable final Configurable configurable, final Configurable oldConfigurable) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } public ActionCallback onModifiedAdded(final Configurable configurable) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } public ActionCallback onModifiedRemoved(final Configurable configurable) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } public ActionCallback onErrorsChanged() { - return new ActionCallback.Done(); + return ActionCallback.DONE; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorContext.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorContext.java index 885c6287338a..ca6272d5cb8b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorContext.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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,8 +17,8 @@ package com.intellij.openapi.options.newEditor; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; -import com.intellij.openapi.util.MultiValuesMap; import com.intellij.openapi.util.ActionCallback; +import com.intellij.openapi.util.MultiValuesMap; import com.intellij.ui.speedSearch.ElementFilter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -45,7 +45,7 @@ public class OptionsEditorContext { } ActionCallback fireSelected(@Nullable final Configurable configurable, @NotNull OptionsEditorColleague requestor) { - if (myCurrentConfigurable == configurable) return new ActionCallback.Rejected(); + if (myCurrentConfigurable == configurable) return ActionCallback.REJECTED; final Configurable old = myCurrentConfigurable; myCurrentConfigurable = configurable; @@ -59,7 +59,7 @@ public class OptionsEditorContext { } ActionCallback fireModifiedAdded(@NotNull final Configurable configurable, @Nullable OptionsEditorColleague requestor) { - if (myModified.contains(configurable)) return new ActionCallback.Rejected(); + if (myModified.contains(configurable)) return ActionCallback.REJECTED; myModified.add(configurable); @@ -72,7 +72,7 @@ public class OptionsEditorContext { } ActionCallback fireModifiedRemoved(@NotNull final Configurable configurable, @Nullable OptionsEditorColleague requestor) { - if (!myModified.contains(configurable)) return new ActionCallback.Rejected(); + if (!myModified.contains(configurable)) return ActionCallback.REJECTED; myModified.remove(configurable); @@ -84,7 +84,7 @@ public class OptionsEditorContext { } ActionCallback fireErrorsChanged(final Map errors, OptionsEditorColleague requestor) { - if (myErrors.equals(errors)) return new ActionCallback.Rejected(); + if (myErrors.equals(errors)) return ActionCallback.REJECTED; myErrors = errors != null ? errors : new HashMap(); diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorDialog.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorDialog.java index 6a9a953cfc9f..13ea327f7b86 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsEditorDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -112,19 +112,19 @@ public class OptionsEditorDialog extends DialogWrapper implements DataProvider{ @Override public ActionCallback onModifiedAdded(final Configurable configurable) { updateStatus(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override public ActionCallback onModifiedRemoved(final Configurable configurable) { updateStatus(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override public ActionCallback onErrorsChanged() { updateStatus(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } }); Disposer.register(myDisposable, myEditor); diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsTree.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsTree.java index ce76b1f19d47..5579651fe705 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsTree.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsTree.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -151,7 +151,7 @@ public class OptionsTree extends JPanel implements Disposable, OptionsEditorColl ActionCallback queueSelection(final Configurable configurable) { if (myBuilder.isSelectionBeingAdjusted()) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } final ActionCallback callback = new ActionCallback(); @@ -585,16 +585,16 @@ public class OptionsTree extends JPanel implements Disposable, OptionsEditorColl public ActionCallback onModifiedAdded(final Configurable colleague) { myTree.repaint(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } public ActionCallback onModifiedRemoved(final Configurable configurable) { myTree.repaint(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } public ActionCallback onErrorsChanged() { - return new ActionCallback.Done(); + return ActionCallback.DONE; } public void processTextEvent(KeyEvent e) { diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsFilter.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsFilter.java index 0818cb6d176f..248eb2a42fdf 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsFilter.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -144,7 +144,7 @@ abstract class SettingsFilter extends ElementFilter.Active.Impl { private ActionCallback update(DocumentEvent.EventType type, boolean adjustSelection, boolean now) { if (myUpdateRejected) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } String text = getFilterText(); if (text.isEmpty()) { diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsTreeView.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsTreeView.java index 9f7b1bc70e4d..7148e6fa837f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsTreeView.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/SettingsTreeView.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -325,7 +325,7 @@ final class SettingsTreeView extends JComponent implements Disposable, OptionsEd ActionCallback select(@Nullable final Configurable configurable) { if (myBuilder.isSelectionBeingAdjusted()) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } final ActionCallback callback = new ActionCallback(); myQueuedConfigurable = configurable; @@ -392,18 +392,18 @@ final class SettingsTreeView extends JComponent implements Disposable, OptionsEd @Override public ActionCallback onModifiedAdded(Configurable configurable) { myTree.repaint(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override public ActionCallback onModifiedRemoved(Configurable configurable) { myTree.repaint(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override public ActionCallback onErrorsChanged() { - return new ActionCallback.Done(); + return ActionCallback.DONE; } private final class MyRoot extends CachingSimpleNode { diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/impl/GlassPaneDialogWrapperPeer.java b/platform/platform-impl/src/com/intellij/openapi/ui/impl/GlassPaneDialogWrapperPeer.java index 156a44ef0dea..a0438ce43736 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/impl/GlassPaneDialogWrapperPeer.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/impl/GlassPaneDialogWrapperPeer.java @@ -327,7 +327,7 @@ public class GlassPaneDialogWrapperPeer extends DialogWrapperPeer implements Foc myDialog.setVisible(true); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AbstractCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AbstractCommand.java index 270374ba6c3d..e393cd17508e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AbstractCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/AbstractCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -90,7 +90,7 @@ public abstract class AbstractCommand implements PlaybackCommand { } catch (Throwable e) { context.error(e.getMessage(), getLine()); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ActionCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ActionCommand.java index d45fe2c8b032..79ae07d343d3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ActionCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ActionCommand.java @@ -45,7 +45,7 @@ public class ActionCommand extends TypeCommand { final AnAction targetAction = am.getAction(actionName); if (targetAction == null) { dumpError(context, "Unknown action: " + actionName); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CallCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CallCommand.java index 910c44d8f9a1..1cb672fcfcd8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CallCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CallCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -45,13 +45,13 @@ public class CallCommand extends AbstractCommand { final int open = cmd.indexOf("("); if (open == -1) { context.error("( expected", getLine()); - return new ActionCallback.Done(); + return ActionCallback.DONE; } final int close = cmd.lastIndexOf(")"); if (close == -1) { context.error(") expected", getLine()); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @@ -69,14 +69,14 @@ public class CallCommand extends AbstractCommand { Pair methodClass = findMethod(context, methodName, types); if (methodClass == null) { context.error("No method \"" + methodName + "\" found in facade classes: " + context.getCallClasses(), getLine()); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } Method m = methodClass.getFirst(); if (!m.getReturnType().isAssignableFrom(AsyncResult.class)) { context.error("Method " + methodClass.getSecond() + ":" + methodName + " must return AsyncResult object", getLine()); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } Object[] actualArgs = noArgs ? new Object[1] : new Object[args.length + 1]; @@ -87,7 +87,7 @@ public class CallCommand extends AbstractCommand { AsyncResult result = (AsyncResult)m.invoke(null, actualArgs); if (result == null) { context.error("Method " + methodClass.getSecond() + ":" + methodName + " must return AsyncResult object, but was null", getLine()); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } result.doWhenDone(new Consumer() { diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CdCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CdCommand.java index 7f6e4177982b..76f974bab3f4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CdCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/CdCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2015 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,7 @@ public class CdCommand extends AbstractCommand { File file = context.getPathMacro().resolveFile(myDir, context.getBaseDir()); if (!file.exists()) { context.message("Cannot cd, directory doesn't exist: " + file.getAbsoluteFile(), getLine()); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } try { @@ -54,6 +54,6 @@ public class CdCommand extends AbstractCommand { } context.message("{base.dir} set to " + context.getBaseDir().getAbsolutePath(), getLine()); - return new ActionCallback.Done(); + return ActionCallback.DONE; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/DelayCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/DelayCommand.java index ba773d4534ed..0c461b4190d6 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/DelayCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/DelayCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -34,9 +34,9 @@ public class DelayCommand extends AbstractCommand { } catch (NumberFormatException e) { dumpError(context, "Invalid delay value: " + s); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } - return new ActionCallback.Done(); + return ActionCallback.DONE; } } \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/EmptyCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/EmptyCommand.java index b27654f19f04..e09fecbd5d1d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/EmptyCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/EmptyCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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,6 +24,6 @@ public class EmptyCommand extends AbstractCommand { } public ActionCallback _execute(PlaybackContext context) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } } \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ErrorCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ErrorCommand.java index 93c1ee3292e5..6abaf117e486 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ErrorCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ErrorCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -26,6 +26,6 @@ public class ErrorCommand extends AbstractCommand { public ActionCallback _execute(PlaybackContext context) { dumpError(context, getText()); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } } \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/KeyShortcutCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/KeyShortcutCommand.java index 5031ec37d904..840bbc3ed219 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/KeyShortcutCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/KeyShortcutCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -31,11 +31,11 @@ public class KeyShortcutCommand extends TypeCommand { final String one = getText().substring(PREFIX.length()); if (!one.endsWith(POSTFIX)) { dumpError(context, "Expected " + "]"); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } type(context.getRobot(), getFromShortcut(one.substring(0, one.length() - 1).trim())); - return new ActionCallback.Done(); + return ActionCallback.DONE; } } \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PopStage.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PopStage.java index 811480640cb3..fbec58a97163 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PopStage.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PopStage.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -34,7 +34,7 @@ public class PopStage extends AbstractCommand { context.test("Test finished OK: " + stage.getName(), getLine()); context.addPassed(stage); } - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PrintCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PrintCommand.java index 68cf05a8bbfb..20ae38186c3b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PrintCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PrintCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -37,6 +37,6 @@ public class PrintCommand extends AbstractCommand { @Override protected ActionCallback _execute(PlaybackContext context) { context.code(myText, getLine()); - return new ActionCallback.Done(); + return ActionCallback.DONE; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PushStage.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PushStage.java index 5031ded8c3e1..a88f18c2612a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PushStage.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/PushStage.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2015 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 @@ public class PushStage extends AbstractCommand { String name = getText().substring(PREFIX.length()).trim(); context.test("Test started: " + name, getLine()); context.pushStage(new StageInfo(name)); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/RegistryValueCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/RegistryValueCommand.java index b4f7b2fbd1b0..b3354ab5c995 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/RegistryValueCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/RegistryValueCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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 @@ public class RegistryValueCommand extends AbstractCommand { final String[] keyValue = getText().substring(PREFIX.length()).trim().split("="); if (keyValue.length != 2) { context.error("Expected expresstion: " + PREFIX + " key=value", getLine()); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } final String key = keyValue[0]; @@ -42,6 +42,6 @@ public class RegistryValueCommand extends AbstractCommand { Registry.get(key).setValue(value); - return new ActionCallback.Done(); + return ActionCallback.DONE; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/StopCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/StopCommand.java index 1d122fe47ebb..be03a3797889 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/StopCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/StopCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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,7 +28,7 @@ public class StopCommand extends AbstractCommand { protected ActionCallback _execute(PlaybackContext context) { context.message("Stopped", getLine()); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ToggleActionCommand.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ToggleActionCommand.java index 8f8e9e09b1ee..ba32a4d85742 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ToggleActionCommand.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/commands/ToggleActionCommand.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -50,7 +50,7 @@ public class ToggleActionCommand extends AbstractCommand { String syntaxText = "Syntax error, expected: " + PREFIX + " " + ON + "|" + OFF + " actionName"; if (args.length != 2) { context.error(syntaxText, getLine()); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } final boolean on; @@ -60,19 +60,19 @@ public class ToggleActionCommand extends AbstractCommand { on = false; } else { context.error(syntaxText, getLine()); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } String actionId = args[1]; final AnAction action = ActionManager.getInstance().getAction(actionId); if (action == null) { context.error("Unknown action id=" + actionId, getLine()); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } if (!(action instanceof ToggleAction)) { context.error("Action is not a toggle action id=" + actionId, getLine()); - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } final InputEvent inputEvent = ActionCommand.getInputEvent(actionId); diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java index 7269997487e8..0bd7e313df41 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -1013,7 +1013,7 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { @NotNull @Override public ActionCallback requestFocus(@NotNull Component c, boolean forced) { - final ActionCallback result = isExpired() ? new ActionCallback.Rejected() : myManager.requestFocus(c, forced); + final ActionCallback result = isExpired() ? ActionCallback.REJECTED : myManager.requestFocus(c, forced); result.doWhenProcessed(new Runnable() { @Override public void run() { @@ -1030,7 +1030,7 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { @NotNull @Override public ActionCallback requestFocus(@NotNull FocusCommand command, boolean forced) { - return isExpired() ? new ActionCallback.Rejected() : myManager.requestFocus(command, forced); + return isExpired() ? ActionCallback.REJECTED : myManager.requestFocus(command, forced); } @Override @@ -1186,7 +1186,7 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { } - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerHeadless.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerHeadless.java index 766cf95bd81b..7b545578bc10 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerHeadless.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerHeadless.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -36,13 +36,13 @@ public class IdeFocusManagerHeadless extends IdeFocusManager { @Override @NotNull public ActionCallback requestFocus(@NotNull final Component c, final boolean forced) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @NotNull public ActionCallback requestFocus(@NotNull final FocusCommand command, final boolean forced) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -84,7 +84,7 @@ public class IdeFocusManagerHeadless extends IdeFocusManager { @Override @NotNull public ActionCallback requestDefaultFocus(boolean forced) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeadlessManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeadlessManagerImpl.java index d8954bc4da89..6683ed0973ad 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeadlessManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeadlessManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -304,7 +304,7 @@ public class ToolWindowHeadlessManagerImpl extends ToolWindowManagerEx { @NotNull @Override public ActionCallback getReady(@NotNull Object requestor) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -446,7 +446,7 @@ public class ToolWindowHeadlessManagerImpl extends ToolWindowManagerEx { @Override public ActionCallback getActivation() { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -497,7 +497,7 @@ public class ToolWindowHeadlessManagerImpl extends ToolWindowManagerEx { @NotNull @Override public ActionCallback getReady(@NotNull Object requestor) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -666,7 +666,7 @@ public class ToolWindowHeadlessManagerImpl extends ToolWindowManagerEx { @Override public ActionCallback removeContent(@NotNull Content content, boolean dispose, boolean trackFocus, boolean implicitFocus) { removeContent(content, dispose); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -682,12 +682,12 @@ public class ToolWindowHeadlessManagerImpl extends ToolWindowManagerEx { @Override public ActionCallback selectNextContent() { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override public ActionCallback selectPreviousContent() { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -704,7 +704,7 @@ public class ToolWindowHeadlessManagerImpl extends ToolWindowManagerEx { @Override public ActionCallback setSelectedContentCB(@NotNull Content content) { setSelectedContent(content); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override @@ -738,7 +738,7 @@ public class ToolWindowHeadlessManagerImpl extends ToolWindowManagerEx { @NotNull @Override public ActionCallback requestFocus(@Nullable final Content content, final boolean forced) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowImpl.java index 149470b60933..9833aabd12e7 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -74,7 +74,7 @@ public final class ToolWindowImpl implements ToolWindowEx { private ToolWindowFactory myContentFactory; @NotNull - private ActionCallback myActivation = new ActionCallback.Done(); + private ActionCallback myActivation = ActionCallback.DONE; private final BusyObject.Impl myShowing = new BusyObject.Impl() { @Override public boolean isReady() { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java index 8a20d8b1897d..96fe52a91bb4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java @@ -639,7 +639,7 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements @Override public ActionCallback run() { runnable.run(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } }.setExpirable(runnable), forced); } @@ -690,7 +690,7 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements activateToolWindow(myActiveStack.peek(), false, true); } } - return new ActionCallback.Done(); + return ActionCallback.DONE; } }, false); } @@ -1840,7 +1840,7 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements } private ActionCallback appendRequestFocusInEditorComponentCmd(List commandList, boolean forced) { - if (myProject.isDisposed()) return new ActionCallback.Done(); + if (myProject.isDisposed()) return ActionCallback.DONE; EditorsSplitters splitters = getSplittersToFocus(); CommandProcessor commandProcessor = myWindowManager.getCommandProcessor(); RequestFocusInEditorComponentCmd command = new RequestFocusInEditorComponentCmd(splitters, getFocusManager(), commandProcessor, forced); @@ -2480,7 +2480,7 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements activateToolWindow(activeId, forced, true); } - return new ActionCallback.Done(); + return ActionCallback.DONE; } Window activeWindow = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); if (activeWindow != null) { @@ -2496,13 +2496,13 @@ public final class ToolWindowManagerImpl extends ToolWindowManagerEx implements JComponent toFocus = IdeFocusTraversalPolicy.getPreferredFocusedComponent(root); if (toFocus != null) { if (DialogWrapper.findInstance(toFocus) != null) { - return new ActionCallback.Done(); //IDEA-80929 + return ActionCallback.DONE; //IDEA-80929 } return IdeFocusManager.findInstanceByComponent(toFocus).requestFocus(toFocus, forced); } } } - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java index c8f542133149..62d6cc4978a8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -174,7 +174,7 @@ public final class RequestFocusInToolWindowCmd extends FinalizableCommand { @Override @NotNull public ActionCallback run() { - return new ActionCallback.Done(); + return ActionCallback.DONE; } }, myForced).doWhenProcessed(new Runnable() { @Override diff --git a/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java b/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java index 2f60475e6b80..359c219fc72b 100644 --- a/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java @@ -450,7 +450,7 @@ public class BalloonImpl implements Balloon, IdeTooltip.Ui { myFocusManager = IdeFocusManager.findInstanceByComponent(myLayeredPane); final Ref originalFocusOwner = new Ref(); final Ref focusRequestor = new Ref(); - final Ref proxyFocusRequest = new Ref(new ActionCallback.Done()); + final Ref proxyFocusRequest = new Ref(ActionCallback.DONE); boolean mnemonicsFix = myDialogMode && SystemInfo.isMac && Registry.is("ide.mac.inplaceDialogMnemonicsFix"); if (mnemonicsFix) { diff --git a/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java b/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java index 8905c88ed95a..b9bc4de59b62 100644 --- a/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java +++ b/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -249,7 +249,7 @@ public class FocusTrackback { private ActionCallback _restoreFocus() { final List stack = getCleanStack(); - if (!stack.contains(this)) return new ActionCallback.Rejected(); + if (!stack.contains(this)) return ActionCallback.REJECTED; Component toFocus = queryToFocus(stack, this, true); diff --git a/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java b/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java index 11385f145ede..a6903fd03646 100644 --- a/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/content/impl/ContentManagerImpl.java @@ -117,9 +117,9 @@ public class ContentManagerImpl implements ContentManager, PropertyChangeListene @Override public ActionCallback getReady(@NotNull Object requestor) { Content selected = getSelectedContent(); - if (selected == null) return new ActionCallback.Done(); + if (selected == null) return ActionCallback.DONE; BusyObject busyObject = selected.getBusyObject(); - return busyObject != null ? busyObject.getReady(requestor) : new ActionCallback.Done(); + return busyObject != null ? busyObject.getReady(requestor) : ActionCallback.DONE; } private class MyNonOpaquePanel extends NonOpaquePanel implements DataProvider { @@ -249,17 +249,17 @@ public class ContentManagerImpl implements ContentManager, PropertyChangeListene private ActionCallback removeContent(@NotNull Content content, boolean trackSelection, boolean dispose) { ApplicationManager.getApplication().assertIsDispatchThread(); int indexToBeRemoved = getIndexOfContent(content); - if (indexToBeRemoved == -1) return new ActionCallback.Rejected(); + if (indexToBeRemoved == -1) return ActionCallback.REJECTED; try { Content selection = mySelection.isEmpty() ? null : mySelection.get(mySelection.size() - 1); int selectedIndex = selection != null ? myContents.indexOf(selection) : -1; if (!fireContentRemoveQuery(content, indexToBeRemoved, ContentManagerEvent.ContentOperation.undefined)) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } if (!content.isValid()) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } boolean wasSelected = isSelected(content); @@ -497,7 +497,7 @@ public class ContentManagerImpl implements ContentManager, PropertyChangeListene } if (!checkSelectionChangeShouldBeProcessed(content, implicit)) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } if (!myContents.contains(content)) { throw new IllegalArgumentException("Cannot find content:" + content.getDisplayName()); @@ -511,7 +511,7 @@ public class ContentManagerImpl implements ContentManager, PropertyChangeListene @NotNull @Override public ActionCallback run() { - if (myDisposed || getIndexOfContent(content) == -1) return new ActionCallback.Rejected(); + if (myDisposed || getIndexOfContent(content) == -1) return ActionCallback.REJECTED; for (Content each : old) { removeFromSelection(each); @@ -522,7 +522,7 @@ public class ContentManagerImpl implements ContentManager, PropertyChangeListene if (requestFocus) { return requestFocus(content, forcedFocus); } - return new ActionCallback.Done(); + return ActionCallback.DONE; } }; @@ -636,7 +636,7 @@ public class ContentManagerImpl implements ContentManager, PropertyChangeListene @Override public ActionCallback requestFocus(final Content content, final boolean forced) { final Content toSelect = content == null ? getSelectedContent() : content; - if (toSelect == null) return new ActionCallback.Rejected(); + if (toSelect == null) return ActionCallback.REJECTED; assert myContents.contains(toSelect); @@ -660,7 +660,7 @@ public class ContentManagerImpl implements ContentManager, PropertyChangeListene toFocus.requestFocus(); } - return new ActionCallback.Done(); + return ActionCallback.DONE; } private static JComponent computeWillFocusComponent(Content toSelect) { diff --git a/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java b/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java index 015a7e6c1bb5..f9846da94b4b 100644 --- a/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java +++ b/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java @@ -931,7 +931,7 @@ public class AbstractPopup implements JBPopup { public ActionCallback run() { if (isDisposed()) { removeActivity(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } _requestFocus(); @@ -961,14 +961,14 @@ public class AbstractPopup implements JBPopup { @Override public ActionCallback run() { if (isDisposed()) { - return new ActionCallback.Rejected(); + return ActionCallback.REJECTED; } _requestFocus(); afterShowRunnable.run(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } }, true).notify(result).doWhenProcessed(new Runnable() { @Override @@ -1181,7 +1181,7 @@ public class AbstractPopup implements JBPopup { @Override public ActionCallback run() { _requestFocus(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } }, true); diff --git a/platform/structure-view-api/src/com/intellij/ide/util/treeView/AbstractTreeStructure.java b/platform/structure-view-api/src/com/intellij/ide/util/treeView/AbstractTreeStructure.java index acd6548ff26d..262ab06fc625 100644 --- a/platform/structure-view-api/src/com/intellij/ide/util/treeView/AbstractTreeStructure.java +++ b/platform/structure-view-api/src/com/intellij/ide/util/treeView/AbstractTreeStructure.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -37,10 +37,10 @@ public abstract class AbstractTreeStructure { @NotNull public static ActionCallback asyncCommitDocuments(@NotNull Project project) { - if (project.isDisposed()) return new ActionCallback.Done(); + if (project.isDisposed()) return ActionCallback.DONE; PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); if (!documentManager.hasUncommitedDocuments()) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } final ActionCallback callback = new ActionCallback(); documentManager.performWhenAllCommitted(callback.createSetDoneRunnable()); @@ -57,7 +57,7 @@ public abstract class AbstractTreeStructure { @NotNull public ActionCallback asyncCommit() { if (hasSomethingToCommit()) commit(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } public boolean isToBuildChildrenInBackground(Object element){ diff --git a/platform/testFramework/src/com/intellij/mock/Mock.java b/platform/testFramework/src/com/intellij/mock/Mock.java index cae264c57d41..7d8006932eeb 100644 --- a/platform/testFramework/src/com/intellij/mock/Mock.java +++ b/platform/testFramework/src/com/intellij/mock/Mock.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2015 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,7 +28,10 @@ import com.intellij.openapi.fileEditor.impl.EditorsSplitters; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.Balloon; -import com.intellij.openapi.util.*; +import com.intellij.openapi.util.ActionCallback; +import com.intellij.openapi.util.AsyncResult; +import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileSystem; import com.intellij.openapi.wm.IdeFocusManager; @@ -147,13 +150,13 @@ public class Mock { @Override public ActionCallback notifyPublisher(@NotNull Runnable runnable) { runnable.run(); - return new ActionCallback.Done(); + return ActionCallback.DONE; } @NotNull @Override public ActionCallback getReady(@NotNull Object requestor) { - return new ActionCallback.Done(); + return ActionCallback.DONE; } @NotNull diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenAttachSourcesProvider.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenAttachSourcesProvider.java index 83b7077273d0..17c4d2beacfa 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenAttachSourcesProvider.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenAttachSourcesProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2015 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. @@ -66,12 +66,14 @@ public class MavenAttachSourcesProvider implements AttachSourcesProvider { public ActionCallback perform(List orderEntries) { // may have been changed by this time... Collection mavenProjects = getMavenProjects(psiFile); - if (mavenProjects.isEmpty()) return new ActionCallback.Rejected(); + if (mavenProjects.isEmpty()) { + return ActionCallback.REJECTED; + } MavenProjectsManager manager = MavenProjectsManager.getInstance(psiFile.getProject()); Collection artifacts = findArtifacts(mavenProjects, orderEntries); - if (artifacts.isEmpty()) return new ActionCallback.Rejected(); + if (artifacts.isEmpty()) return ActionCallback.REJECTED; final AsyncResult result = new AsyncResult(); manager.scheduleArtifactsDownloading(mavenProjects, artifacts, true, false, result); From 2bd319ad86a53d479c0b52ad2c7abebae6f339ee Mon Sep 17 00:00:00 2001 From: Eugene Zhuravlev Date: Mon, 20 Jul 2015 19:44:29 +0200 Subject: [PATCH 068/106] handling duplicate entries in modules.xml --- .../jps/model/serialization/JpsProjectLoader.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java index e9f6409d88c2..3227eefd6aa0 100644 --- a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java +++ b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java @@ -23,6 +23,7 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.util.ArrayUtil; import com.intellij.util.concurrency.BoundedTaskExecutor; +import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -48,9 +49,7 @@ import org.jetbrains.jps.service.SharedThreadPool; import java.io.File; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.Future; @@ -220,7 +219,7 @@ public class JpsProjectLoader extends JpsLoaderBase { Element componentRoot = JDomSerializationUtil.findComponent(root, "ProjectModuleManager"); if (componentRoot == null) return; - List moduleFiles = new ArrayList(); + final Set moduleFiles = new THashSet(FileUtil.FILE_HASHING_STRATEGY); for (Element moduleElement : JDOMUtil.getChildren(componentRoot.getChild("modules"), "module")) { final String path = moduleElement.getAttributeValue("filepath"); final File file = new File(path); @@ -240,7 +239,7 @@ public class JpsProjectLoader extends JpsLoaderBase { } @NotNull - public static List loadModules(@NotNull List moduleFiles, @Nullable final JpsSdkType projectSdkType, + public static List loadModules(@NotNull Collection moduleFiles, @Nullable final JpsSdkType projectSdkType, @NotNull final Map pathVariables) { List modules = new ArrayList(); List>> futureModuleFilesContents = new ArrayList>>(); From 9bfea86ceaea768148415680a759dd32e1a8cae3 Mon Sep 17 00:00:00 2001 From: "Maxim.Mossienko" Date: Mon, 20 Jul 2015 19:50:14 +0200 Subject: [PATCH 069/106] license for plexus-classworlds, btw codehaus repos had moved to github --- build/scripts/libLicenses.gant | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build/scripts/libLicenses.gant b/build/scripts/libLicenses.gant index 51e007771587..a175d5ced874 100644 --- a/build/scripts/libLicenses.gant +++ b/build/scripts/libLicenses.gant @@ -210,7 +210,8 @@ libraryLicense(name: "markdownj", libraryName: "markdownj", version: "0.4.2", li libraryLicense(name: "markdown4j", libraryName: "markdown4j-2.2", version: "2.2", license: "New BSD", url: "https://code.google.com/p/markdown4j/", licenseUrl: "http://opensource.org/licenses/BSD-3-Clause") libraryLicense(name: "Maven", version: "2.2.1", license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html") libraryLicense(name: "plexus-util", version: "2.0.6", license: "Apache 2.0", url: "http://maven.apache.org/", libraryNames:['plexus-utils-2.0.6.jar'], licenseUrl: "http://apache.org/licenses/LICENSE-2.0") -libraryLicense(name: "plexus-archiver", libraryName: "plexus-archiver-2.4.4.jar", version: "2.4.4", license: "Apache 2.0", url: "http://plexus.codehaus.org/plexus-components/plexus-archiver", licenseUrl: "http://apache.org/licenses/LICENSE-2.0") +libraryLicense(name: "plexus-archiver", libraryName: "plexus-archiver-2.4.4.jar", version: "2.4.4", license: "Apache 2.0", url: "https://github.com/codehaus-plexus/plexus-archiver", licenseUrl: "http://apache.org/licenses/LICENSE-2.0") +libraryLicense(name: "plexus-classworlds", libraryName: "plexus-classworlds-2.4.jar", version: "2.4", license: "Apache 2.0", url: "https://github.com/codehaus-plexus/plexus-classworlds", licenseUrl: "http://apache.org/licenses/LICENSE-2.0") libraryLicense(name: "aether-api", version: "1.13.1", libraryNames: ["aether-api-1.13.1.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html") libraryLicense(name: "aether-api-0.9.0.M2.jar", version: "0.9.0.M2", libraryNames: ["aether-api-0.9.0.M2.jar"], license: "Eclipse Public License v1.0", url: "http://nexus.sonatype.org/", licenseUrl: "http://www.eclipse.org/org/documents/epl-v10.html") libraryLicense(name: "maven-2.2.1-uber", version: "2.2.1", libraryNames: ["maven-2.2.1-uber.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html") From a68b1ab38bf9aa1b6347bc72b8fd18d583cb176a Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 17:46:48 +0200 Subject: [PATCH 070/106] IDEA-137372 Live templates speed search matching can honor group name in addition to the template prefix --- .../codeInsight/template/impl/LiveTemplateTree.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateTree.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateTree.java index 29f835193636..c54d9b837980 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateTree.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateTree.java @@ -75,10 +75,9 @@ class LiveTemplateTree extends CheckboxTree implements DataProvider, CopyProvide } if (object instanceof TemplateImpl) { TemplateImpl template = (TemplateImpl)object; - return StringUtil.notNullize(template.getKey()) + - " " + - StringUtil.notNullize(template.getDescription()) + - " " + + return StringUtil.notNullize(template.getGroupName()) + " " + + StringUtil.notNullize(template.getKey()) + " " + + StringUtil.notNullize(template.getDescription()) + " " + template.getTemplateText(); } return ""; From d4eebb6401097a5e2d6f3db271915db4c23a9d5f Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 17:52:01 +0200 Subject: [PATCH 071/106] tolerate malformed fqns in java completion (EA-63095 - IOE: PsiJavaParserFacadeImpl.createExpressionFromText) --- .../codeInsight/completion/JavaCompletionUtil.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java index f099bf1ccabd..970dc0459783 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java @@ -665,9 +665,15 @@ public class JavaCompletionUtil { if (psiClass.isValid() && !psiClass.getManager().areElementsEquivalent(psiClass, resolveReference(ref))) { final boolean staticImport = ref instanceof PsiImportStaticReferenceElement; - PsiElement newElement = staticImport - ? ((PsiImportStaticReferenceElement)ref).bindToTargetClass(psiClass) - : ref.bindToElement(psiClass); + PsiElement newElement; + try { + newElement = staticImport + ? ((PsiImportStaticReferenceElement)ref).bindToTargetClass(psiClass) + : ref.bindToElement(psiClass); + } + catch (IncorrectOperationException e) { + return endOffset; // can happen if fqn contains reserved words, for example + } final RangeMarker rangeMarker = document.createRangeMarker(newElement.getTextRange()); documentManager.doPostponedOperationsAndUnblockDocument(document); From 5616345fbc5e0b518a5ceec291149b3c47a1dec6 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 18:13:07 +0200 Subject: [PATCH 072/106] don't stop whole search on error in some file, diagnose PSI file range inconsistency (EA-53915 - assert: LowLevelSearchUtil.processElementsContainingWordInElement) --- .../psi/impl/search/LowLevelSearchUtil.java | 39 ++++++++++++++++--- 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/platform/indexing-impl/src/com/intellij/psi/impl/search/LowLevelSearchUtil.java b/platform/indexing-impl/src/com/intellij/psi/impl/search/LowLevelSearchUtil.java index e600b6d720d0..bd14596b7305 100644 --- a/platform/indexing-impl/src/com/intellij/psi/impl/search/LowLevelSearchUtil.java +++ b/platform/indexing-impl/src/com/intellij/psi/impl/search/LowLevelSearchUtil.java @@ -17,15 +17,17 @@ package com.intellij.psi.impl.search; import com.intellij.lang.ASTNode; +import com.intellij.lang.Language; import com.intellij.lang.injection.InjectedLanguageManager; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.editor.Document; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiLanguageInjectionHost; +import com.intellij.psi.*; +import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.tree.LeafElement; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.search.TextOccurenceProcessor; @@ -38,6 +40,7 @@ import org.jetbrains.annotations.Nullable; import java.util.List; public class LowLevelSearchUtil { + private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.LowLevelSearchUtil"); // TRUE/FALSE -> injected psi has been discovered and processor returned true/false; // null -> there were nothing injected found @@ -173,18 +176,21 @@ public class LowLevelSearchUtil { if (progress != null) progress.checkCanceled(); PsiFile file = scope.getContainingFile(); - final CharSequence buffer = file.getViewProvider().getContents(); + FileViewProvider viewProvider = file.getViewProvider(); + final CharSequence buffer = viewProvider.getContents(); TextRange range = scope.getTextRange(); if (range == null) { - throw new AssertionError("Element " + scope + " of class " + scope.getClass() + " has null range"); + LOG.error("Element " + scope + " of class " + scope.getClass() + " has null range"); + return true; } int scopeStart = range.getStartOffset(); int startOffset = scopeStart; int endOffset = range.getEndOffset(); if (endOffset > buffer.length()) { - throw new AssertionError("Range for element: '"+scope+"' = "+range+" is out of file '" + file + "' range: " + file.getTextRange()+"; file contents length: "+buffer.length()+"; file provider: "+file.getViewProvider()); + diagnoseInvalidRange(scope, file, viewProvider, buffer, range); + return true; } final char[] bufferArray = CharArrayUtil.fromSequenceWithoutCopying(buffer); @@ -207,6 +213,27 @@ public class LowLevelSearchUtil { return true; } + private static void diagnoseInvalidRange(@NotNull PsiElement scope, + PsiFile file, + FileViewProvider viewProvider, + CharSequence buffer, + TextRange range) { + String msg = "Range for element: '" + scope + "' = " + range + " is out of file '" + file + "' range: " + file.getTextRange(); + msg += "; file contents length: " + buffer.length(); + msg += "\n file provider: " + viewProvider; + Document document = viewProvider.getDocument(); + if (document != null) { + msg += "\n committed=" + PsiDocumentManager.getInstance(file.getProject()).isCommitted(document); + } + for (Language language : viewProvider.getLanguages()) { + final PsiFile root = viewProvider.getPsi(language); + msg += "\n root " + language + " length=" + root.getTextLength() + (root instanceof PsiFileImpl + ? "; contentsLoaded=" + ((PsiFileImpl)root).isContentsLoaded() : ""); + } + + LOG.error(msg); + } + public static int searchWord(@NotNull CharSequence text, int startOffset, int endOffset, From 6132f4f7a5bebbb3ec1da2645b3bf2fd7af0721f Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 18:50:35 +0200 Subject: [PATCH 073/106] don't require java file copy to be java (EA-70418 - assert: PsiJavaFileBaseImpl.clone) --- .../psi/impl/source/PsiJavaFileBaseImpl.java | 12 ------------ .../com/intellij/psi/impl/source/PsiFileImpl.java | 2 ++ 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java index d0a665a9e2e4..102a452f167a 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java @@ -50,7 +50,6 @@ import com.intellij.util.containers.MostlySingularMultiMap; import com.intellij.util.indexing.IndexingDataKeys; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; @@ -67,17 +66,6 @@ public abstract class PsiJavaFileBaseImpl extends PsiFileImpl implements PsiJava myResolveCache = CachedValuesManager.getManager(myManager.getProject()).createCachedValue(new MyCacheBuilder(this), false); } - @Override - @SuppressWarnings({"CloneDoesntDeclareCloneNotSupportedException"}) - protected PsiJavaFileBaseImpl clone() { - PsiFileImpl clone = super.clone(); - if (!(clone instanceof PsiJavaFileBaseImpl)) { - throw new AssertionError("Java file cloned as text: " + getTextLength() + "; " + getViewProvider()); - } - clone.clearCaches(); - return (PsiJavaFileBaseImpl)clone; - } - @Override public void subtreeChanged() { super.subtreeChanged(); diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java b/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java index 63d0fcb9388d..55b22017c6f8 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java +++ b/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java @@ -458,6 +458,8 @@ public abstract class PsiFileImpl extends ElementBase implements PsiFileEx, PsiF else if (myOriginalFile != null) { clone.myOriginalFile = myOriginalFile; } + + clone.clearCaches(); return clone; } From 54c229a9b6ac93d45204e74bc7ffe200e92c09d1 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 18:59:01 +0200 Subject: [PATCH 074/106] LibraryDependentToolWindowManager: be prepared to PCE from index access (EA-70872 - PCE: FileBasedIndexImpl.checkRebuild) --- .../impl/LibraryDependentToolWindowManager.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java index 26864b326b12..15f30a184924 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java @@ -3,6 +3,7 @@ package com.intellij.openapi.wm.impl; import com.intellij.ProjectTopics; import com.intellij.openapi.components.AbstractProjectComponent; import com.intellij.openapi.extensions.Extensions; +import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootAdapter; @@ -12,7 +13,6 @@ import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.ext.LibraryDependentToolWindow; -import com.intellij.psi.PsiManager; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; @@ -51,12 +51,16 @@ public class LibraryDependentToolWindowManager extends AbstractProjectComponent DumbService.getInstance(project).smartInvokeLater(new Runnable() { public void run() { - final PsiManager psiManager = PsiManager.getInstance(myProject); - if (psiManager.isDisposed()) { - return; - } for (LibraryDependentToolWindow libraryToolWindow : Extensions.getExtensions(LibraryDependentToolWindow.EXTENSION_POINT_NAME)) { - if (libraryToolWindow.getLibrarySearchHelper().isLibraryExists(project)) { + boolean exists; + try { + exists = libraryToolWindow.getLibrarySearchHelper().isLibraryExists(project); + } + catch (ProcessCanceledException e) { + exists = false; + DumbService.getInstance(project).smartInvokeLater(this); + } + if (exists) { ensureToolWindowExists(libraryToolWindow); } else { From 26b7e75ef49c518b5bf3b08021a746240ae2381d Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 19:02:53 +0200 Subject: [PATCH 075/106] FinderRecursivePanel: handle EA-70298 - INRE: FileBasedIndexImpl.handleDumbMode --- .../src/com/intellij/ui/FinderRecursivePanel.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java b/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java index f67026d22c10..4331a877ffbd 100644 --- a/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java +++ b/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java @@ -23,6 +23,7 @@ import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.project.DumbService; +import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; @@ -353,7 +354,12 @@ public abstract class FinderRecursivePanel extends JBSplitter implements Data //noinspection unchecked final T t = (T)value; setIcon(getItemIcon(t)); - append(getItemText(t)); + try { + append(getItemText(t)); + } + catch (IndexNotReadyException e) { + append("loading..."); + } doCustomizeCellRenderer(this, list, t, index, isSelected, cellHasFocus); From 85f94d9c2899f2274412afe0f2b94ddaae088099 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 19:14:41 +0200 Subject: [PATCH 076/106] concurrent root iteration on startup should be under a progress that's canceled on project closing (EA-68060 - assert: DirectoryIndexImpl.checkAvailability) --- .../impl/PushedFilePropertiesUpdaterImpl.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java b/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java index 455a7212ca6f..dbb3cfdd6e5e 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java @@ -28,6 +28,7 @@ import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; +import com.intellij.openapi.progress.util.ProgressWrapper; import com.intellij.openapi.project.DumbModeTask; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; @@ -298,14 +299,23 @@ public class PushedFilePropertiesUpdaterImpl extends PushedFilePropertiesUpdater for(Runnable r:tasks) r.run(); return; } + + final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); + assert progress != null; + final ConcurrentLinkedQueue tasksQueue = new ConcurrentLinkedQueue(tasks); Future result = null; if (tasks.size() > 1) { result = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @Override public void run() { - Runnable runnable; - while ((runnable = tasksQueue.poll()) != null) runnable.run(); + ProgressManager.getInstance().runProcess(new Runnable() { + @Override + public void run() { + Runnable runnable; + while ((runnable = tasksQueue.poll()) != null) runnable.run(); + } + }, ProgressWrapper.wrap(progress)); } }); } From c91b9950a29f89321a4e002db384a0f03cb9e92f Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 19:24:32 +0200 Subject: [PATCH 077/106] don't use stale PsiFile in InspectionValidatorWrapper (EA-66085 - PIEAE: PsiScopesUtil.treeWalkUp) --- .../util/InspectionValidatorWrapper.java | 55 +++++++++++-------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/java/compiler/impl/src/com/intellij/openapi/compiler/util/InspectionValidatorWrapper.java b/java/compiler/impl/src/com/intellij/openapi/compiler/util/InspectionValidatorWrapper.java index 0abbe05a2173..c2577f5410d5 100644 --- a/java/compiler/impl/src/com/intellij/openapi/compiler/util/InspectionValidatorWrapper.java +++ b/java/compiler/impl/src/com/intellij/openapi/compiler/util/InspectionValidatorWrapper.java @@ -96,12 +96,12 @@ public class InspectionValidatorWrapper implements Validator { private class MyValidatorProcessingItem implements ProcessingItem { private final VirtualFile myVirtualFile; - private final PsiFile myPsiFile; + private final PsiManager myPsiManager; private PsiElementsValidityState myValidityState; public MyValidatorProcessingItem(@NotNull final PsiFile psiFile) { - myPsiFile = psiFile; myVirtualFile = psiFile.getVirtualFile(); + myPsiManager = psiFile.getManager(); } @Override @@ -121,14 +121,18 @@ public class InspectionValidatorWrapper implements Validator { private PsiElementsValidityState computeValidityState() { final PsiElementsValidityState state = new PsiElementsValidityState(); - for (PsiElement psiElement : myValidator.getDependencies(myPsiFile)) { - state.addDependency(psiElement); + final PsiFile psiFile = getPsiFile(); + if (psiFile != null) { + for (PsiElement psiElement : myValidator.getDependencies(psiFile)) { + state.addDependency(psiElement); + } } return state; } + @Nullable public PsiFile getPsiFile() { - return myPsiFile; + return myPsiManager.findFile(myVirtualFile); } } @@ -205,7 +209,7 @@ public class InspectionValidatorWrapper implements Validator { try { ourCompilationThreads.set(Boolean.TRUE); - if (checkFile(inspections, item.getPsiFile(), context)) { + if (checkFile(inspections, item, context)) { processedItems.add(item); } } @@ -217,20 +221,21 @@ public class InspectionValidatorWrapper implements Validator { return processedItems.toArray(new ProcessingItem[processedItems.size()]); } - private boolean checkFile(List inspections, final PsiFile file, final CompileContext context) { + private boolean checkFile(List inspections, final MyValidatorProcessingItem item, final CompileContext context) { boolean hasErrors = false; - if (!checkUnderReadAction(file, context, new Computable>() { + if (!checkUnderReadAction(item, context, new Computable>() { @Override public Map compute() { - return myValidator.checkAdditionally(file); + return myValidator.checkAdditionally(item.getPsiFile()); } })) { hasErrors = true; } - if (!checkUnderReadAction(file, context, new Computable>() { + if (!checkUnderReadAction(item, context, new Computable>() { @Override public Map compute() { + final PsiFile file = item.getPsiFile(); if (file instanceof XmlFile) { return runXmlFileSchemaValidation((XmlFile)file); } @@ -243,10 +248,11 @@ public class InspectionValidatorWrapper implements Validator { final InspectionProfile inspectionProfile = myProfileManager.getInspectionProfile(); for (final LocalInspectionTool inspectionTool : inspections) { - if (!checkUnderReadAction(file, context, new Computable>() { + if (!checkUnderReadAction(item, context, new Computable>() { @Override public Map compute() { - if (getHighlightDisplayLevel(inspectionTool, inspectionProfile, file) != HighlightDisplayLevel.DO_NOT_SHOW) { + final PsiFile file = item.getPsiFile(); + if (file != null && getHighlightDisplayLevel(inspectionTool, inspectionProfile, file) != HighlightDisplayLevel.DO_NOT_SHOW) { return runInspectionTool(file, inspectionTool, getHighlightDisplayLevel(inspectionTool, inspectionProfile, file) ); } @@ -259,11 +265,12 @@ public class InspectionValidatorWrapper implements Validator { return !hasErrors; } - private boolean checkUnderReadAction(final PsiFile file, final CompileContext context, final Computable> runnable) { + private boolean checkUnderReadAction(final MyValidatorProcessingItem item, final CompileContext context, final Computable> runnable) { return DumbService.getInstance(context.getProject()).runReadActionInSmartMode(new Computable() { @Override public Boolean compute() { - if (!file.isValid()) return false; + final PsiFile file = item.getPsiFile(); + if (file == null) return false; final Document document = myPsiDocumentManager.getCachedDocument(file); if (document != null && myPsiDocumentManager.isUncommited(document)) { @@ -340,14 +347,8 @@ public class InspectionValidatorWrapper implements Validator { final AnnotationHolderImpl holder = new AnnotationHolderImpl(new AnnotationSession(xmlFile)); final List annotators = ExternalLanguageAnnotators.allForFile(StdLanguages.XML, xmlFile); - for (ExternalAnnotator annotator : annotators) { - Object initial = annotator.collectInformation(xmlFile); - if (initial != null) { - Object result = annotator.doAnnotate(initial); - if (result != null) { - annotator.apply(xmlFile, result, holder); - } - } + for (ExternalAnnotator annotator : annotators) { + processAnnotator(xmlFile, holder, annotator); } if (!holder.hasAnnotations()) return Collections.emptyMap(); @@ -370,6 +371,16 @@ public class InspectionValidatorWrapper implements Validator { return problemsMap; } + private static void processAnnotator(@NotNull XmlFile xmlFile, AnnotationHolderImpl holder, ExternalAnnotator annotator) { + X initial = annotator.collectInformation(xmlFile); + if (initial != null) { + Y result = annotator.doAnnotate(initial); + if (result != null) { + annotator.apply(xmlFile, result, holder); + } + } + } + @Override @NotNull From ea07addeee4012faef640ea6ee194e95750e621f Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 19:33:53 +0200 Subject: [PATCH 078/106] run choose by name bg calculation in smart mode (EA-65609 - INRE: FileBasedIndexImpl.handleDumbMode) --- .../ide/util/gotoByName/ChooseByNameBase.java | 13 ++++++++++- .../progress/util/ProgressIndicatorUtils.java | 7 +----- .../openapi/progress/util/ReadTask.java | 22 ++++++++++++++++--- 3 files changed, 32 insertions(+), 10 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java index 5536a5eca418..62944c67c93e 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java @@ -49,6 +49,7 @@ import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.openapi.progress.util.ProgressIndicatorUtils; import com.intellij.openapi.progress.util.ReadTask; import com.intellij.openapi.progress.util.TooManyUsagesStatus; +import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.*; import com.intellij.openapi.util.*; @@ -1494,7 +1495,7 @@ public abstract class ChooseByNameBase { return panel; } - private class CalcElementsThread implements ReadTask { + private class CalcElementsThread extends ReadTask { private final String myPattern; private final boolean myCheckboxState; private final Consumer> myCallback; @@ -1521,6 +1522,16 @@ public abstract class ChooseByNameBase { ProgressIndicatorUtils.scheduleWithWriteActionPriority(myProgress, this); } + @Override + public void runBackgroundProcess(@NotNull final ProgressIndicator indicator) { + DumbService.getInstance(myProject).runReadActionInSmartMode(new Runnable() { + @Override + public void run() { + computeInReadAction(indicator); + } + }); + } + @Override public void computeInReadAction(@NotNull ProgressIndicator indicator) { if (myProject != null && myProject.isDisposed()) return; diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressIndicatorUtils.java b/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressIndicatorUtils.java index eb7405b386ab..d448f5470229 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressIndicatorUtils.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressIndicatorUtils.java @@ -176,12 +176,7 @@ public class ProgressIndicatorUtils { @Override public void run() { try { - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - task.computeInReadAction(progressIndicator); - } - }); + task.runBackgroundProcess(progressIndicator); } catch (ProcessCanceledException ignore) { } diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/util/ReadTask.java b/platform/platform-impl/src/com/intellij/openapi/progress/util/ReadTask.java index 07e3a800df32..fb18e3a29860 100644 --- a/platform/platform-impl/src/com/intellij/openapi/progress/util/ReadTask.java +++ b/platform/platform-impl/src/com/intellij/openapi/progress/util/ReadTask.java @@ -15,6 +15,8 @@ */ package com.intellij.openapi.progress.util; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import org.jetbrains.annotations.NotNull; @@ -24,17 +26,31 @@ import org.jetbrains.annotations.NotNull; * @see com.intellij.openapi.progress.util.ProgressIndicatorUtils#scheduleWithWriteActionPriority(ReadTask) * */ -public interface ReadTask { +public abstract class ReadTask { /** * Performs the computation. * Is invoked inside a read action and under a progress indicator that's canceled when a write action is about to occur. */ - void computeInReadAction(@NotNull ProgressIndicator indicator); + public abstract void computeInReadAction(@NotNull ProgressIndicator indicator) throws ProcessCanceledException; /** * Is invoked on Swing thread whenever the computation is canceled by a write action. * A likely implementation is to restart the computation, maybe based on the new state of the system. */ - void onCanceled(@NotNull ProgressIndicator indicator); + public abstract void onCanceled(@NotNull ProgressIndicator indicator); + /** + * Is invoked on a background thread. The responsibility of this method is to start a read action and + * call {@link #computeInReadAction(ProgressIndicator)}. Overriders might also do something else. + * For example, use {@link com.intellij.openapi.project.DumbService#runReadActionInSmartMode(Runnable)}. + * @param indicator the progress indicator of the background thread + */ + public void runBackgroundProcess(@NotNull final ProgressIndicator indicator) throws ProcessCanceledException { + ApplicationManager.getApplication().runReadAction(new Runnable() { + @Override + public void run() { + computeInReadAction(indicator); + } + }); + } } From 3dbda0ae18411321e20862491b510cefcc4c75f8 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 19:40:24 +0200 Subject: [PATCH 079/106] ObjectsRequireNonNullIntention: don't delete external/inferred annotations (EA-63847 - PIEAE: PsiUtilCore.ensureValid) --- .../siyeh/ipp/asserttoif/ObjectsRequireNonNullIntention.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/asserttoif/ObjectsRequireNonNullIntention.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/asserttoif/ObjectsRequireNonNullIntention.java index e3617711d6c0..920c713f6096 100644 --- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/asserttoif/ObjectsRequireNonNullIntention.java +++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/asserttoif/ObjectsRequireNonNullIntention.java @@ -110,7 +110,8 @@ public class ObjectsRequireNonNullIntention extends Intention { if (ClassUtils.findClass("java.util.Objects", element) == null) { return false; } - if (NullableNotNullManager.isNotNull(variable)) { + final PsiAnnotation annotation = NullableNotNullManager.getInstance(variable.getProject()).getNotNullAnnotation(variable, true); + if (annotation != null && annotation.isWritable()) { return true; } final PsiStatement referenceStatement = PsiTreeUtil.getParentOfType(referenceExpression, PsiStatement.class); From bf87a7466a67e2c3e70d3b8cc9a68826f37e4e80 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 19:40:36 +0200 Subject: [PATCH 080/106] diagnose invalid type's annotations (EA-63847 - PIEAE: PsiUtilCore.ensureValid) --- java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java b/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java index 26d23a2ade10..9e571eeb2ad1 100644 --- a/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java @@ -1186,6 +1186,14 @@ public final class PsiUtil extends PsiUtilCore { } throw new AssertionError("Invalid type: " + type + " of class " + type.getClass() + " " + customMessage); } + for (PsiAnnotation annotation : type.getAnnotations()) { + try { + PsiUtilCore.ensureValid(annotation); + } + catch (PsiInvalidElementAccessException e) { + throw customMessage == null? e : new RuntimeException(customMessage, e); + } + } } @Nullable From eaa5d2a80b7872038800c93dfa978ce24f1e69fc Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 19:47:09 +0200 Subject: [PATCH 081/106] IDEA-128290 Allow cancelling directory creation if specified name contains dot remove mnemonic from Cancel (IDEA-CR-3834) --- .../intellij/ide/actions/CreateDirectoryOrPackageHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java b/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java index f5c99d5b9f09..47f5035ac78e 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java @@ -163,7 +163,7 @@ public class CreateDirectoryOrPackageHandler implements InputValidatorEx { "File Name Detected", "&Yes, create file", "&No, create " + (myIsDirectory ? "directory" : "packages"), - "&Cancel", + CommonBundle.getCancelButtonText(), fileType.getIcon()); if (ec == Messages.CANCEL) { return false; From 3bf473593f47a5613ee81f031aff96087fba7588 Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 21:06:56 +0200 Subject: [PATCH 082/106] make JBUI to support floating scale factor --- .../util/src/com/intellij/util/ui/JBUI.java | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/platform/util/src/com/intellij/util/ui/JBUI.java b/platform/util/src/com/intellij/util/ui/JBUI.java index c0aea56e2448..d2f1c4b6751b 100644 --- a/platform/util/src/com/intellij/util/ui/JBUI.java +++ b/platform/util/src/com/intellij/util/ui/JBUI.java @@ -29,6 +29,7 @@ import java.awt.*; */ public class JBUI { private static boolean IS_HIDPI = calculateHiDPI(); + private static float SCALE_FACTOR = calculateScaleFactor(); private static boolean calculateHiDPI() { if (SystemInfo.isMac) { @@ -50,6 +51,24 @@ public class JBUI { return false; } + private static float calculateScaleFactor() { + if (SystemInfo.isMac) { + return 1.0f; + } + + if (SystemProperties.has("hidpi") && !SystemProperties.is("hidpi")) { + return 1.0f; + } + + final int dpi = getSystemDPI(); + if (dpi <= 96) return 1.0f; + if (dpi <= 120) return 1.25f; + if (dpi <= 144) return 1.5f; + if (dpi <= 168) return 1.75f; + + return 2.0f; + } + private static int getSystemDPI() { try { return Toolkit.getDefaultToolkit().getScreenResolution(); @@ -59,7 +78,7 @@ public class JBUI { } public static int scale(int i) { - return isHiDPI() ? 2 * i : i; + return (int)(SCALE_FACTOR * i); } public static JBDimension size(int width, int height) { @@ -115,7 +134,7 @@ public class JBUI { } public static float scale(float f) { - return f * scale(1); + return f * SCALE_FACTOR; } public static JBInsets insets(Insets insets) { @@ -123,7 +142,7 @@ public class JBUI { } public static boolean isHiDPI() { - return IS_HIDPI; + return SCALE_FACTOR > 1.0f; } public static class Fonts { From c6eced45431a55bc6dfc3f695fbd051dde44e680 Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 21:08:57 +0200 Subject: [PATCH 083/106] add dependency: module util -> imgscalr lib --- platform/util/util.iml | 1 + 1 file changed, 1 insertion(+) diff --git a/platform/util/util.iml b/platform/util/util.iml index 45eeefec5d1a..119eaca9e79c 100644 --- a/platform/util/util.iml +++ b/platform/util/util.iml @@ -23,6 +23,7 @@ + From 97a52bbff4350ec0dfddb34e78b247c80ae51655 Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 21:12:31 +0200 Subject: [PATCH 084/106] ImageLoader: support fractional upscaling/downscaling for various DPI settings --- .../src/com/intellij/util/ImageLoader.java | 34 ++++++++++++------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/platform/util/src/com/intellij/util/ImageLoader.java b/platform/util/src/com/intellij/util/ImageLoader.java index b8ac405c97f3..2b01aacbaf49 100644 --- a/platform/util/src/com/intellij/util/ImageLoader.java +++ b/platform/util/src/com/intellij/util/ImageLoader.java @@ -22,16 +22,16 @@ import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.util.io.URLUtil; +import com.intellij.util.ui.ImageUtil; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; +import org.imgscalr.Scalr; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; @@ -63,14 +63,21 @@ public class ImageLoader implements Serializable { @Nullable public static Image loadFromUrl(@NotNull URL url) { + return loadFromUrl(url, true); + } + + @Nullable + public static Image loadFromUrl(@NotNull URL url, boolean allowFloatScaling) { for (Pair each : getFileNames(url.toString())) { try { Image image = loadFromStream(URLUtil.openStream(new URL(each.first)), each.second); - + float scale = allowFloatScaling ? JBUI.scale(1f) : JBUI.scale(1f) > 1.5f ? 2f : 1f; //we can't check all 3rd party plugins and convince the authors to add @2x icons. // isHiDPI() != isRetina() => we should scale images manually if (image != null && JBUI.isHiDPI() && !each.first.contains("@2x")) { - image = upscale(image); + image = upscale(image, scale); + } else if (image != null && JBUI.scale(1f) >= 1.5f && JBUI.scale(1f) < 2.0f && each.first.contains("@2x")) { + image = downscale(image, scale); } return image; } @@ -81,16 +88,17 @@ public class ImageLoader implements Serializable { } @NotNull - private static Image upscale(Image image) { - float scale = JBUI.scale(1f); + private static Image upscale(Image image, float scale) { int width = (int)(scale * image.getWidth(null)); int height = (int)(scale * image.getHeight(null)); - @SuppressWarnings("UndesirableClassUsage") - BufferedImage tmp = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = tmp.createGraphics(); - g.drawImage(image, AffineTransform.getScaleInstance(scale, scale), null); - image = tmp; - return image; + return Scalr.resize(ImageUtil.toBufferedImage(image), Scalr.Method.ULTRA_QUALITY, width, height); + } + + @NotNull + private static Image downscale(Image image, float scale) { + int width = (int)(image.getWidth(null) / 2f * scale); + int height = (int)(image.getHeight(null)/ 2f * scale); + return Scalr.resize(ImageUtil.toBufferedImage(image), Scalr.Method.ULTRA_QUALITY, width, height); } @Nullable @@ -124,7 +132,7 @@ public class ImageLoader implements Serializable { } public static List> getFileNames(@NotNull String file) { - return getFileNames(file, UIUtil.isUnderDarcula(), UIUtil.isRetina() || JBUI.isHiDPI()); + return getFileNames(file, UIUtil.isUnderDarcula(), UIUtil.isRetina() || JBUI.scale(1.0f) >= 1.5f); } public static List> getFileNames(@NotNull String file, boolean dark, boolean retina) { From d2c69b1e16d911aefbda3255f80a78a02574ec18 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Mon, 20 Jul 2015 22:09:53 +0300 Subject: [PATCH 085/106] EA-68122 - NPE: InspectionToolsConfigurable.getPreferredFocusedComponent --- .../codeInspection/ui/header/InspectionToolsConfigurable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/InspectionToolsConfigurable.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/InspectionToolsConfigurable.java index d59cd1a1fda8..da658ced7c2a 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/InspectionToolsConfigurable.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/InspectionToolsConfigurable.java @@ -668,7 +668,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable @Override public JComponent getPreferredFocusedComponent() { - final InspectionProfileImpl inspectionProfile = getSelectedObject(); + final InspectionProfileImpl inspectionProfile = myProfiles.getSelectedProfile(); SingleInspectionProfilePanel panel = getProfilePanel(inspectionProfile); return panel == null ? null : panel.getPreferredFocusedComponent(); } From b742ecc9d1da281d0e6a303b4e53d0624dc2f0aa Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 21:13:55 +0200 Subject: [PATCH 086/106] fix progress indicator glitches on Splash for non-standard DPIs --- platform/platform-impl/src/com/intellij/ui/Splash.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/ui/Splash.java b/platform/platform-impl/src/com/intellij/ui/Splash.java index 621c0ffec4de..27b4dc4b714d 100644 --- a/platform/platform-impl/src/com/intellij/ui/Splash.java +++ b/platform/platform-impl/src/com/intellij/ui/Splash.java @@ -16,7 +16,6 @@ package com.intellij.ui; import com.intellij.ide.StartupProgress; -import com.intellij.ide.ui.UISettings; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.util.IconLoader; @@ -99,7 +98,7 @@ public class Splash extends JDialog implements StartupProgress { this(info.getSplashImageUrl(), info.getSplashTextColor()); if (info instanceof ApplicationInfoImpl) { final ApplicationInfoImpl appInfo = (ApplicationInfoImpl)info; - myProgressHeight = JBUI.scale(2); + myProgressHeight = 2 * Math.round(JBUI.scale(0.99f)); myProgressColor = appInfo.getProgressColor(); myProgressY = appInfo.getProgressY(); myProgressTail = appInfo.getProgressTailIcon(); @@ -140,8 +139,8 @@ public class Splash extends JDialog implements StartupProgress { g.setColor(color); g.fillRect(1, getProgressY(), width, getProgressHeight()); if (myProgressTail != null) { - myProgressTail.paintIcon(this, g, width - (myProgressTail.getIconWidth() / JBUI.scale(1) / 2 * JBUI.scale(1)), - getProgressY() - (myProgressTail.getIconHeight() - getProgressHeight()) / JBUI.scale(1) / 2 * JBUI.scale(1)); //I'll buy you a beer if you understand this line without playing with it + myProgressTail.paintIcon(this, g, (int)(width - (myProgressTail.getIconWidth() / JBUI.scale(1f) / 2f * JBUI.scale(1f))), + (int)(getProgressY() - (myProgressTail.getIconHeight() - getProgressHeight()) / JBUI.scale(1f) / 2f * JBUI.scale(1f))); //I'll buy you a beer if you understand this line without playing with it } myProgressLastPosition = progressWidth; } @@ -155,7 +154,7 @@ public class Splash extends JDialog implements StartupProgress { } private int getProgressY() { - return JBUI.scale(myProgressY); + return (int)JBUI.scale((float)myProgressY); } public static boolean showLicenseeInfo(Graphics g, int x, int y, final int height, final Color textColor) { From 82e88489a44805cc70b7ca9e87230e522d6725db Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 21:15:31 +0200 Subject: [PATCH 087/106] update Splash tail icon size 13x13 -> 16x16 for optimal upscaling --- .../src/community_progress_tail.png | Bin 299 -> 309 bytes python/resources/community_progress_tail.png | Bin 299 -> 309 bytes 2 files changed, 0 insertions(+), 0 deletions(-) diff --git a/community-resources/src/community_progress_tail.png b/community-resources/src/community_progress_tail.png index 7750f4841743090c738ffb4936b7b97181025b7e..be210582c9eb3c9d98b98e467436502fbe6decdc 100644 GIT binary patch literal 309 zcmV-50m}Y~P)z?8!H=XlnSpTUP>gQ5RIr53WY|c(I|8j9^m(%n3ZEK#g}Y$ z=9|o%83jP$(uiZl_=u|nNhjGPCD?J0Jji$gcE)jq(v*z?8!H=XlnSpTUP>gQ5RIr53WY|c(I|8j9^m(%n3ZEK#g}Y$ z=9|o%83jP$(uiZl_=u|nNhjGPCD?J0Jji$gcE)jq(v* Date: Mon, 20 Jul 2015 21:16:38 +0200 Subject: [PATCH 088/106] return raw tail icon (no upscale) from App Info --- .../openapi/application/impl/ApplicationInfoImpl.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java b/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java index 7714b585193c..dde556ddeee8 100644 --- a/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java +++ b/platform/core-impl/src/com/intellij/openapi/application/impl/ApplicationInfoImpl.java @@ -26,6 +26,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.JBColor; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; +import com.intellij.util.ImageLoader; import com.intellij.util.PlatformUtils; import com.intellij.util.containers.ContainerUtil; import org.jdom.Document; @@ -37,6 +38,7 @@ import javax.swing.*; import java.awt.*; import java.io.File; import java.io.FileNotFoundException; +import java.net.URL; import java.text.MessageFormat; import java.util.*; import java.util.List; @@ -319,7 +321,13 @@ public class ApplicationInfoImpl extends ApplicationInfoEx implements JDOMExtern @Nullable public Icon getProgressTailIcon() { if (myProgressTailIcon == null && myProgressTailIconName != null) { - myProgressTailIcon = IconLoader.getIcon(myProgressTailIconName); + try { + final URL url = getClass().getResource(myProgressTailIconName); + final Image image = ImageLoader.loadFromUrl(url, false); + if (image != null) { + myProgressTailIcon = new ImageIcon(image); + } + } catch (Exception ignore) {} } return myProgressTailIcon; } From 560b61a3be713fed15f137d5b7d10c828f06dc47 Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 21:18:17 +0200 Subject: [PATCH 089/106] HiDPI: wrap status bar constants with JBUI.scale --- .../src/com/intellij/openapi/wm/StatusBarWidget.java | 6 +++--- .../intellij/openapi/wm/impl/status/IdeStatusBarImpl.java | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/platform/platform-api/src/com/intellij/openapi/wm/StatusBarWidget.java b/platform/platform-api/src/com/intellij/openapi/wm/StatusBarWidget.java index 1350f09b5304..5f312bf2e519 100644 --- a/platform/platform-api/src/com/intellij/openapi/wm/StatusBarWidget.java +++ b/platform/platform-api/src/com/intellij/openapi/wm/StatusBarWidget.java @@ -17,8 +17,8 @@ package com.intellij.openapi.wm; import com.intellij.openapi.Disposable; import com.intellij.openapi.ui.popup.ListPopup; -import com.intellij.ui.IdeBorderFactory; import com.intellij.util.Consumer; +import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -83,7 +83,7 @@ public interface StatusBarWidget extends Disposable { } abstract class WidgetBorder implements Border { - public static final Border INSTANCE = IdeBorderFactory.createEmptyBorder(0, 2, 0, 2); - public static final Border WIDE = IdeBorderFactory.createEmptyBorder(0, 4, 0, 4); + public static final Border INSTANCE = JBUI.Borders.empty(0, 2); + public static final Border WIDE = JBUI.Borders.empty(0, 4); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java index 0b0c8112bad6..29ead452db04 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java @@ -54,7 +54,7 @@ import java.util.List; * User: spLeaner */ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { - private static final int MIN_ICON_HEIGHT = 18 + 1 + 1; + private static final int MIN_ICON_HEIGHT = JBUI.scale(18 + 1 + 1); private final InfoAndProgressPanel myInfoAndProgressPanel; private IdeFrame myFrame; From dec3365aac292c81f13bc32a4175cab7a108f78c Mon Sep 17 00:00:00 2001 From: "Maxim.Mossienko" Date: Mon, 20 Jul 2015 21:15:28 +0200 Subject: [PATCH 090/106] removed assertion, it doesn't hold for tests --- .../openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java | 1 - 1 file changed, 1 deletion(-) diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java b/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java index dbb3cfdd6e5e..4f27cb072c8d 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdaterImpl.java @@ -301,7 +301,6 @@ public class PushedFilePropertiesUpdaterImpl extends PushedFilePropertiesUpdater } final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - assert progress != null; final ConcurrentLinkedQueue tasksQueue = new ConcurrentLinkedQueue(tasks); Future result = null; From 81c7cea628105d927b00acd6e29f40c3e99098b5 Mon Sep 17 00:00:00 2001 From: Vladimir Krivosheev Date: Mon, 20 Jul 2015 21:19:16 +0200 Subject: [PATCH 091/106] public to avoid error if packed into different jars --- .../src/com/intellij/ui/switcher/SwitchManager.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java b/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java index af2b4d529966..7a5c24ab9e7b 100644 --- a/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java +++ b/platform/platform-api/src/com/intellij/ui/switcher/SwitchManager.java @@ -51,7 +51,10 @@ public class SwitchManager { myQa = quickAccess; } - boolean dispatchKeyEvent(@NotNull KeyEvent e) { + /** + * internal use only + */ + public boolean dispatchKeyEvent(@NotNull KeyEvent e) { if (isSessionActive()) { return false; } From 92dae51b129bf5f3dde9901a49e00c0451a9a4f2 Mon Sep 17 00:00:00 2001 From: Eugene Zhuravlev Date: Mon, 20 Jul 2015 21:29:09 +0200 Subject: [PATCH 092/106] fixing tests --- .../model/serialization/JpsProjectLoader.java | 1 + .../JpsProjectSerializationTest.java | 47 +++++++++++++++---- 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java index 3227eefd6aa0..ac42e6304f86 100644 --- a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java +++ b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java @@ -220,6 +220,7 @@ public class JpsProjectLoader extends JpsLoaderBase { if (componentRoot == null) return; final Set moduleFiles = new THashSet(FileUtil.FILE_HASHING_STRATEGY); + //final List moduleFiles = new ArrayList(); for (Element moduleElement : JDOMUtil.getChildren(componentRoot.getChild("modules"), "module")) { final String path = moduleElement.getAttributeValue("filepath"); final File file = new File(path); diff --git a/jps/model-serialization/testSrc/org/jetbrains/jps/model/serialization/JpsProjectSerializationTest.java b/jps/model-serialization/testSrc/org/jetbrains/jps/model/serialization/JpsProjectSerializationTest.java index 11fd9c14a968..72ac2d456ed8 100644 --- a/jps/model-serialization/testSrc/org/jetbrains/jps/model/serialization/JpsProjectSerializationTest.java +++ b/jps/model-serialization/testSrc/org/jetbrains/jps/model/serialization/JpsProjectSerializationTest.java @@ -49,12 +49,28 @@ public class JpsProjectSerializationTest extends JpsSerializationTestCase { assertEquals("sampleProjectName", myProject.getName()); List modules = myProject.getModules(); assertEquals(3, modules.size()); - JpsModule main = modules.get(0); - assertEquals("main", main.getName()); - JpsModule util = modules.get(1); - assertEquals("util", util.getName()); - JpsModule xxx = modules.get(2); - assertEquals("xxx", xxx.getName()); + + JpsModule main = null; + JpsModule xxx = null; + JpsModule util = null; + for (JpsModule module : modules) { + final String name = module.getName(); + if ("main".equals(name)) { + main = module; + } + else if ("util".equals(name)) { + util = module; + } + else if ("xxx".equals(name)) { + xxx = module; + } + else { + fail("Unexpected module name " + name); + } + } + assertNotNull("module 'main' was not loaded", main); + assertNotNull("module 'util' was not loaded", util); + assertNotNull("module 'xxx' was not loaded", xxx); assertTrue(FileUtil.filesEqual(new File(baseDirPath, "util"), JpsModelSerializationDataService.getBaseDirectory(util))); @@ -174,8 +190,23 @@ public class JpsProjectSerializationTest extends JpsSerializationTestCase { public void testSaveProject() { loadProject(SAMPLE_PROJECT_PATH); List modules = myProject.getModules(); - doTestSaveModule(modules.get(0), SAMPLE_PROJECT_PATH + "/main.iml"); - doTestSaveModule(modules.get(1), SAMPLE_PROJECT_PATH + "/util/util.iml"); + + JpsModule main = null, util = null; + for (JpsModule module : modules) { + final String name = module.getName(); + if ("main".equals(name)) { + main = module; + } + else if ("util".equals(name)) { + util = module; + } + } + + assertNotNull(main); + assertNotNull(util); + + doTestSaveModule(main, SAMPLE_PROJECT_PATH + "/main.iml"); + doTestSaveModule(util, SAMPLE_PROJECT_PATH + "/util/util.iml"); //tod[nik] remember that test output root wasn't specified and doesn't save it to avoid unnecessary modifications of iml files //doTestSaveModule(modules.get(2), "xxx/xxx.iml"); From 9b6d017e706dbfd6fd091a8df953c6ba7823d290 Mon Sep 17 00:00:00 2001 From: "Vassiliy.Kudryashov" Date: Mon, 20 Jul 2015 22:34:12 +0300 Subject: [PATCH 093/106] IDEA-81363 Submenu hides (too fast) when leaving entry in main menu tuning --- .../openapi/actionSystem/impl/ActionMenu.java | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java index 8608ce3fb617..e1271558ba70 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java @@ -29,6 +29,7 @@ import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.StatusBar; import com.intellij.ui.plaf.beg.IdeaMenuUI; import com.intellij.ui.plaf.gtk.GtkMenuUI; +import com.intellij.util.SingleAlarm; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; @@ -322,16 +323,27 @@ public final class ActionMenu extends JMenu { } } } - private static class UsabilityHelper implements IdeEventQueue.EventDispatcher, AWTEventListener, Disposable { private Component myComponent; private Point myLastMousePoint = null; private Point myUpperTargetPoint = null; private Point myLowerTargetPoint = null; + private SingleAlarm myCallbackAlarm; + private MouseEvent myEventToRedispatch = null; private UsabilityHelper(Component component, @NotNull Disposable disposable) { Disposer.register(disposable, this); + myCallbackAlarm = new SingleAlarm(new Runnable() { + @Override + public void run() { + Disposer.dispose(myCallbackAlarm); + myCallbackAlarm = null; + if (myEventToRedispatch != null) { + IdeEventQueue.getInstance().dispatchEvent(myEventToRedispatch); + } + } + }, 50, this); myComponent = component; PointerInfo info = MouseInfo.getPointerInfo(); myLastMousePoint = info != null ? info.getLocation() : null; @@ -365,19 +377,25 @@ public final class ActionMenu extends JMenu { @Override public boolean dispatch(AWTEvent e) { - if (e instanceof MouseEvent && myUpperTargetPoint != null && myLowerTargetPoint != null) { + if (e instanceof MouseEvent && myUpperTargetPoint != null && myLowerTargetPoint != null && myCallbackAlarm != null) { if (e.getID() == MouseEvent.MOUSE_PRESSED || e.getID() == MouseEvent.MOUSE_RELEASED || e.getID() == MouseEvent.MOUSE_CLICKED) { return false; } Point point = ((MouseEvent)e).getLocationOnScreen(); - boolean result = new Polygon( + myCallbackAlarm.cancel(); + boolean isMouseMovingTowardsSubmenu = new Polygon( new int[]{myLastMousePoint.x, myUpperTargetPoint.x, myLowerTargetPoint.x}, new int[]{myLastMousePoint.y, myUpperTargetPoint.y, myLowerTargetPoint.y}, 3).contains(point); + myEventToRedispatch = (MouseEvent)e; + + if (!isMouseMovingTowardsSubmenu) { + myCallbackAlarm.request(); + } myLastMousePoint = point; - return result; + return true; } return false; } @@ -385,6 +403,7 @@ public final class ActionMenu extends JMenu { @Override public void dispose() { myComponent = null; + myEventToRedispatch = null; myLastMousePoint = myUpperTargetPoint = myLowerTargetPoint = null; Toolkit.getDefaultToolkit().removeAWTEventListener(this); } From 7b231d5202e6c7cda061320cd0aaa45a4c9652bf Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 21:48:31 +0200 Subject: [PATCH 094/106] MemoryWidget: make constants HiDPI friendly --- .../com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java index 6ca775ddb117..c7a8071b3156 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java @@ -221,8 +221,8 @@ public class MemoryUsagePanel extends JButton implements CustomStatusBarWidget { @Override public Dimension getPreferredSize() { final Insets insets = getInsets(); - int width = getFontMetrics(getWidgetFont()).stringWidth(SAMPLE_STRING) + insets.left + insets.right + 2; - int height = getFontMetrics(getWidgetFont()).getHeight() + insets.top + insets.bottom + 2; + int width = getFontMetrics(getWidgetFont()).stringWidth(SAMPLE_STRING) + insets.left + insets.right + JBUI.scale(2); + int height = getFontMetrics(getWidgetFont()).getHeight() + insets.top + insets.bottom + JBUI.scale(2); return new Dimension(width, height); } From dd828e49a3a80646c2d487eb30d75e051cd4b09a Mon Sep 17 00:00:00 2001 From: Konstantin Bulenkov Date: Mon, 20 Jul 2015 21:49:37 +0200 Subject: [PATCH 095/106] fix double scaling of Status Bar height --- .../com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java index 29ead452db04..0b0c8112bad6 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java @@ -54,7 +54,7 @@ import java.util.List; * User: spLeaner */ public class IdeStatusBarImpl extends JComponent implements StatusBarEx { - private static final int MIN_ICON_HEIGHT = JBUI.scale(18 + 1 + 1); + private static final int MIN_ICON_HEIGHT = 18 + 1 + 1; private final InfoAndProgressPanel myInfoAndProgressPanel; private IdeFrame myFrame; From 42d1b3ec91aa7293a45c003d61e609f03a35a694 Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 21:53:06 +0200 Subject: [PATCH 096/106] restore goto file/action/etc in dumb mode --- .../src/com/intellij/ide/util/TreeFileChooserDialog.java | 3 ++- .../intellij/ide/util/gotoByName/ChooseByNameBase.java | 9 +++++++-- .../intellij/ide/util/gotoByName/GotoActionModel.java | 3 ++- .../com/intellij/ide/util/gotoByName/GotoFileModel.java | 3 ++- .../src/com/intellij/tasks/actions/GotoTaskAction.java | 2 +- 5 files changed, 14 insertions(+), 6 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/ide/util/TreeFileChooserDialog.java b/platform/lang-impl/src/com/intellij/ide/util/TreeFileChooserDialog.java index 7835444472c9..a414b0628a8f 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/TreeFileChooserDialog.java +++ b/platform/lang-impl/src/com/intellij/ide/util/TreeFileChooserDialog.java @@ -33,6 +33,7 @@ import com.intellij.ide.util.treeView.NodeRenderer; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Condition; @@ -367,7 +368,7 @@ public final class TreeFileChooserDialog extends DialogWrapper implements TreeFi return myTree; } - private final class MyGotoFileModel implements ChooseByNameModel { + private final class MyGotoFileModel implements ChooseByNameModel, DumbAware { private final int myMaxSize = WindowManagerEx.getInstanceEx().getFrame(myProject).getSize().width; @Override @NotNull diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java index 62944c67c93e..858d2144dd88 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java @@ -1524,12 +1524,17 @@ public abstract class ChooseByNameBase { @Override public void runBackgroundProcess(@NotNull final ProgressIndicator indicator) { - DumbService.getInstance(myProject).runReadActionInSmartMode(new Runnable() { + Runnable r = new Runnable() { @Override public void run() { computeInReadAction(indicator); } - }); + }; + if (DumbService.isDumbAware(myModel)) { + ApplicationManager.getApplication().runReadAction(r); + } else { + DumbService.getInstance(myProject).runReadActionInSmartMode(r); + } } @Override diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionModel.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionModel.java index 1a4bfa19b67f..2838ab7f0e54 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionModel.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoActionModel.java @@ -32,6 +32,7 @@ import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.SearchableConfigurable; +import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.SystemInfo; @@ -62,7 +63,7 @@ import java.util.List; import static com.intellij.ui.SimpleTextAttributes.STYLE_PLAIN; import static com.intellij.ui.SimpleTextAttributes.STYLE_SEARCH_MATCH; -public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, Comparator, EdtSortingModel { +public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, Comparator, EdtSortingModel, DumbAware { @Nullable private final Project myProject; private final Component myContextComponent; diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoFileModel.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoFileModel.java index 8ba19a815e44..78af0bd1c246 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoFileModel.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoFileModel.java @@ -25,6 +25,7 @@ import com.intellij.navigation.NavigationItem; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.VirtualFile; @@ -40,7 +41,7 @@ import java.util.Collection; /** * Model for "Go to | File" action */ -public class GotoFileModel extends FilteringGotoByModel { +public class GotoFileModel extends FilteringGotoByModel implements DumbAware { private final int myMaxSize; public GotoFileModel(@NotNull Project project) { diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java index 40a9cf04afbc..4710e7a0a3e3 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java @@ -118,7 +118,7 @@ public class GotoTaskAction extends GotoActionBase implements DumbAware { }); } - private static class GotoTaskPopupModel extends SimpleChooseByNameModel { + private static class GotoTaskPopupModel extends SimpleChooseByNameModel implements DumbAware { private ListCellRenderer myListCellRenderer; From 673edc94a65d0e87949d27ce50886dac17a3bf6f Mon Sep 17 00:00:00 2001 From: peter Date: Mon, 20 Jul 2015 23:11:29 +0200 Subject: [PATCH 097/106] InfoAndProgressPanel.removeProgress: assert that the progress was added before --- .../intellij/openapi/wm/impl/status/InfoAndProgressPanel.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java index 877c85b0bd01..3713625dcce9 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java @@ -22,6 +22,7 @@ import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileEditor.impl.EditorsSplitters; import com.intellij.openapi.progress.ProgressIndicator; @@ -61,6 +62,7 @@ import java.util.*; import java.util.List; public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidget { + private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.wm.impl.status.InfoAndProgressPanel"); private final ProcessPopup myPopup; private final StatusPanel myInfoPanel = new StatusPanel(); @@ -234,7 +236,7 @@ public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidge private void removeProgress(@NotNull InlineProgressIndicator progress) { synchronized (myOriginals) { - if (!myInline2Original.containsKey(progress)) return; + LOG.assertTrue(myInline2Original.containsKey(progress)); final boolean last = myOriginals.size() == 1; final boolean beforeLast = myOriginals.size() == 2; From 9284a926d4ff748125400baaf4efc9eebfd2ace7 Mon Sep 17 00:00:00 2001 From: "Maxim.Mossienko" Date: Tue, 21 Jul 2015 00:36:11 +0200 Subject: [PATCH 098/106] faster duplicates index, fix for IDEA-124624 --- .../dupLocator/index/DuplicatesIndex.java | 23 +++++++++++++++---- .../index/DuplicatesInspectionBase.java | 21 +++++++++++++---- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/platform/duplicates-analysis/src/com/intellij/dupLocator/index/DuplicatesIndex.java b/platform/duplicates-analysis/src/com/intellij/dupLocator/index/DuplicatesIndex.java index fc104ec480fb..bbceb2d24059 100644 --- a/platform/duplicates-analysis/src/com/intellij/dupLocator/index/DuplicatesIndex.java +++ b/platform/duplicates-analysis/src/com/intellij/dupLocator/index/DuplicatesIndex.java @@ -54,7 +54,8 @@ import java.util.Map; public class DuplicatesIndex extends FileBasedIndexExtension implements PsiDependentIndex { static boolean ourEnabled = SystemProperties.getBooleanProperty("idea.enable.duplicates.online.calculation", isEnabledByDefault()); - static boolean ourEnabledLightProfiles = true; + static final boolean ourEnabledLightProfiles = true; + private static boolean ourEnabledOldProfiles = false; private static boolean isEnabledByDefault() { Application application = ApplicationManager.getApplication(); @@ -62,12 +63,15 @@ public class DuplicatesIndex extends FileBasedIndexExtension NAME = ID.create("DuplicatesIndex"); - private static final int myBaseVersion = 15; + private static final int myBaseVersion = 16; private final FileBasedIndex.InputFilter myInputFilter = new FileBasedIndex.InputFilter() { @Override public boolean acceptInput(@NotNull final VirtualFile file) { - return ourEnabled && findDuplicatesProfile(file.getFileType()) != null; + return ourEnabled && + findDuplicatesProfile(file.getFileType()) != null && + file.isInLocalFileSystem() // skip library sources + ; } }; @@ -151,12 +155,14 @@ public class DuplicatesIndex extends FileBasedIndexExtension myProcessorRef = new Ref(); final FileASTNode node = psiFile.getNode(); - if (profile instanceof LightDuplicateProfile && node.getElementType() instanceof ILightStubFileElementType && - DuplicatesIndex.ourEnabledLightProfiles) { + boolean usingLightProfile = profile instanceof LightDuplicateProfile && + node.getElementType() instanceof ILightStubFileElementType && + DuplicatesIndex.ourEnabledLightProfiles; + if (usingLightProfile) { LighterAST ast = node.getLighterAST(); assert ast != null; ((LightDuplicateProfile)profile).process(ast, new LightDuplicateProfile.Callback() { @@ -81,6 +83,11 @@ public class DuplicatesInspectionBase extends LocalInspectionTool { protected int getEndOffset(LighterASTNode node) { return node.getEndOffset(); } + + @Override + protected boolean isLightProfile() { + return true; + } } if (myProcessor == null) { myProcessor = new LightDuplicatedCodeProcessor(virtualFile, psiFile.getProject()); @@ -136,6 +143,11 @@ public class DuplicatesInspectionBase extends LocalInspectionTool { protected int getEndOffset(PsiFragment node) { return node.getEndOffset(); } + + @Override + protected boolean isLightProfile() { + return false; + } } if (myProcessor == null) { myProcessor = new OldDuplicatedCodeProcessor(virtualFile, psiFile.getProject()); @@ -154,7 +166,7 @@ public class DuplicatesInspectionBase extends LocalInspectionTool { for(Map.Entry entry:processor.reportedRanges.entrySet()) { final Integer offset = entry.getKey(); // todo 3 statements constant - if (processor.fragmentSize.get(offset) < MIN_FRAGMENT_SIZE) continue; + if (!usingLightProfile && processor.fragmentSize.get(offset) < MIN_FRAGMENT_SIZE) continue; final VirtualFile file = processor.reportedFiles.get(offset); String message = "Found duplicated code in " + file.getPath(); @@ -244,7 +256,7 @@ public class DuplicatesInspectionBase extends LocalInspectionTool { reportedOffsetInOtherFiles.put(fragmentStartOffsetInteger, value); reportedPsi.put(fragmentStartOffsetInteger, target); fragmentSize.put(fragmentStartOffsetInteger, newFragmentSize); - if (newFragmentSize >= MIN_FRAGMENT_SIZE) fragmentHash.put(fragmentStartOffsetInteger, myHash); + if (newFragmentSize >= MIN_FRAGMENT_SIZE || isLightProfile()) fragmentHash.put(fragmentStartOffsetInteger, myHash); return false; } return true; @@ -255,5 +267,6 @@ public class DuplicatesInspectionBase extends LocalInspectionTool { protected abstract int getStartOffset(T node); protected abstract int getEndOffset(T node); + protected abstract boolean isLightProfile(); } } From d7dd6ae7995b0042c72644ffdec7059dc8a99dbb Mon Sep 17 00:00:00 2001 From: Eugene Zhuravlev Date: Tue, 21 Jul 2015 08:42:00 +0200 Subject: [PATCH 099/106] fixing tests --- .../JpsMavenModuleSerializationTest.java | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/plugins/maven/jps-plugin/testSrc/org/jetbrains/jps/maven/model/JpsMavenModuleSerializationTest.java b/plugins/maven/jps-plugin/testSrc/org/jetbrains/jps/maven/model/JpsMavenModuleSerializationTest.java index 8e2690b841c2..c15a480592e5 100644 --- a/plugins/maven/jps-plugin/testSrc/org/jetbrains/jps/maven/model/JpsMavenModuleSerializationTest.java +++ b/plugins/maven/jps-plugin/testSrc/org/jetbrains/jps/maven/model/JpsMavenModuleSerializationTest.java @@ -14,12 +14,29 @@ public class JpsMavenModuleSerializationTest extends JpsSerializationTestCase { loadProject("plugins/maven/jps-plugin/testData/compiler/classpathTest"); List modules = myProject.getModules(); assertEquals(3, modules.size()); - JpsModule main = modules.get(0); - assertEquals("main", main.getName()); - JpsModule dep = modules.get(1); - assertEquals("dep", dep.getName()); - JpsModule depTest = modules.get(2); - assertEquals("dep-test", depTest.getName()); + + JpsModule main = null; + JpsModule dep = null; + JpsModule depTest = null; + for (JpsModule module : modules) { + final String name = module.getName(); + if ("main".equals(name)) { + main = module; + } + else if ("dep-test".equals(name)) { + depTest = module; + } + else if ("dep".equals(name)) { + dep = module; + } + else { + fail("Unexpected module name " + name); + } + } + assertNotNull("module 'main' was not loaded", main); + assertNotNull("module 'depTest' was not loaded", depTest); + assertNotNull("module 'dep' was not loaded", dep); + for (JpsModule module : modules) { assertNotNull(getService().getExtension(module)); From 75e3086fb2d3392135c60fbf7087e9de5772e40e Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Fri, 17 Jul 2015 13:03:10 +0300 Subject: [PATCH 100/106] lambda -> meth ref: reject replacements with invalid qualifiers (IDEA-142695) --- .../LambdaCanBeMethodReferenceInspection.java | 5 ++- .../beforeMethodFromAnonymousClass.java | 39 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/lambda2methodReference/beforeMethodFromAnonymousClass.java diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java index 045a9a0f3c3a..6b0b3b12928c 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java @@ -320,6 +320,7 @@ public class LambdaCanBeMethodReferenceInspection extends BaseJavaBatchLocalInsp return classOrPrimitiveName; } + @Nullable private static String getQualifierTextByMethodCall(final PsiMethodCallExpression methodCall, final PsiType functionalInterfaceType, final PsiParameter[] parameters, @@ -363,6 +364,7 @@ public class LambdaCanBeMethodReferenceInspection extends BaseJavaBatchLocalInsp } } + @Nullable private static String composeReceiverQualifierText(PsiParameter[] parameters, PsiMethod psiMethod, PsiClass containingClass, @@ -400,8 +402,7 @@ public class LambdaCanBeMethodReferenceInspection extends BaseJavaBatchLocalInsp return qualifiedName; } else { - final String containingClassName = containingClass.getName(); - return containingClassName != null ? containingClassName : ""; + return containingClass.getName(); } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/lambda2methodReference/beforeMethodFromAnonymousClass.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/lambda2methodReference/beforeMethodFromAnonymousClass.java new file mode 100644 index 000000000000..50d768919192 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/lambda2methodReference/beforeMethodFromAnonymousClass.java @@ -0,0 +1,39 @@ +// "Replace lambda with method reference" "false" + +import java.util.Arrays; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; + +class Test { + + public static void main(String[] args) { + List l = Arrays.asList("America", "Britain", "Australia", "Brazil", "Canada"); + System.out.println(l); + System.out.println(uniquifyListByProperty(l, Function.identity())); + System.out.println(uniquifyListByProperty(l, s -> s.charAt(0))); + } + + static List uniquifyListByProperty(List list, Function propertyExtractor) { + return list.stream() + .map(item -> new Object() { + @Override + public boolean equals(Object o) { + return propertyExtractor.apply(item).equals( + propertyExtractor.apply(this.getClass().cast(o).item())); + } + + @Override + public int hashCode() { + return propertyExtractor.apply(item).hashCode(); + } + + T item() { + return item; + } + }) + .distinct() + .map(o -> o.item()) + .collect(Collectors.toList()); + } +} From 9501af04f5d3116ff2bf3937e8bc6f4e4a4751c2 Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Sun, 19 Jul 2015 14:39:04 +0300 Subject: [PATCH 101/106] decode: don't qualify 'ambiguous' reference if qualifier is available through inheritance (IDEA-142703) --- .../com/intellij/codeInsight/ChangeContextUtil.java | 5 ++++- .../qualifiedRef/after/p1/StaticMethod.java | 4 ++++ .../moveClass/qualifiedRef/after/p2/Test.java | 12 ++++++++++++ .../moveClass/qualifiedRef/after/p2/empty.txt | 0 .../qualifiedRef/before/p1/StaticMethod.java | 4 ++++ .../moveClass/qualifiedRef/before/p1/Test.java | 10 ++++++++++ .../moveClass/qualifiedRef/before/p2/empty.txt | 0 .../com/intellij/refactoring/MoveClassTest.java | 4 ++++ 8 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 java/java-tests/testData/refactoring/moveClass/qualifiedRef/after/p1/StaticMethod.java create mode 100644 java/java-tests/testData/refactoring/moveClass/qualifiedRef/after/p2/Test.java create mode 100644 java/java-tests/testData/refactoring/moveClass/qualifiedRef/after/p2/empty.txt create mode 100644 java/java-tests/testData/refactoring/moveClass/qualifiedRef/before/p1/StaticMethod.java create mode 100644 java/java-tests/testData/refactoring/moveClass/qualifiedRef/before/p1/Test.java create mode 100644 java/java-tests/testData/refactoring/moveClass/qualifiedRef/before/p2/empty.txt diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/ChangeContextUtil.java b/java/java-psi-impl/src/com/intellij/codeInsight/ChangeContextUtil.java index d79de6646780..a64c2cffef62 100644 --- a/java/java-psi-impl/src/com/intellij/codeInsight/ChangeContextUtil.java +++ b/java/java-psi-impl/src/com/intellij/codeInsight/ChangeContextUtil.java @@ -202,7 +202,10 @@ public class ChangeContextUtil { if (refMember.hasModifierProperty(PsiModifier.STATIC)){ PsiElement refElement = refExpr.resolve(); if (!manager.areElementsEquivalent(refMember, refElement)){ - refExpr.setQualifierExpression(factory.createReferenceExpression(containingClass)); + final PsiClass currentClass = PsiTreeUtil.getParentOfType(refExpr, PsiClass.class); + if (currentClass == null || !InheritanceUtil.isInheritorOrSelf(currentClass, containingClass, true)) { + refExpr.setQualifierExpression(factory.createReferenceExpression(containingClass)); + } } } else { diff --git a/java/java-tests/testData/refactoring/moveClass/qualifiedRef/after/p1/StaticMethod.java b/java/java-tests/testData/refactoring/moveClass/qualifiedRef/after/p1/StaticMethod.java new file mode 100644 index 000000000000..bd1ea3518601 --- /dev/null +++ b/java/java-tests/testData/refactoring/moveClass/qualifiedRef/after/p1/StaticMethod.java @@ -0,0 +1,4 @@ +package p1; +public class StaticMethod { + public static int bar() {return 1;} +} diff --git a/java/java-tests/testData/refactoring/moveClass/qualifiedRef/after/p2/Test.java b/java/java-tests/testData/refactoring/moveClass/qualifiedRef/after/p2/Test.java new file mode 100644 index 000000000000..8cbeea59015b --- /dev/null +++ b/java/java-tests/testData/refactoring/moveClass/qualifiedRef/after/p2/Test.java @@ -0,0 +1,12 @@ +package p2; +import p1.StaticMethod; + +import java.math.BigDecimal; +public class Test extends BigDecimal { + Test() {super(0);} + void test() { + valueOf(0); + valueOf(StaticMethod.bar()); + valueOf(StaticMethod.bar()); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/moveClass/qualifiedRef/after/p2/empty.txt b/java/java-tests/testData/refactoring/moveClass/qualifiedRef/after/p2/empty.txt new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/java/java-tests/testData/refactoring/moveClass/qualifiedRef/before/p1/StaticMethod.java b/java/java-tests/testData/refactoring/moveClass/qualifiedRef/before/p1/StaticMethod.java new file mode 100644 index 000000000000..bd1ea3518601 --- /dev/null +++ b/java/java-tests/testData/refactoring/moveClass/qualifiedRef/before/p1/StaticMethod.java @@ -0,0 +1,4 @@ +package p1; +public class StaticMethod { + public static int bar() {return 1;} +} diff --git a/java/java-tests/testData/refactoring/moveClass/qualifiedRef/before/p1/Test.java b/java/java-tests/testData/refactoring/moveClass/qualifiedRef/before/p1/Test.java new file mode 100644 index 000000000000..0f0d205f652a --- /dev/null +++ b/java/java-tests/testData/refactoring/moveClass/qualifiedRef/before/p1/Test.java @@ -0,0 +1,10 @@ +package p1; +import java.math.BigDecimal; +public class Test extends BigDecimal { + Test() {super(0);} + void test() { + valueOf(0); + valueOf(StaticMethod.bar()); + valueOf(StaticMethod.bar()); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/moveClass/qualifiedRef/before/p2/empty.txt b/java/java-tests/testData/refactoring/moveClass/qualifiedRef/before/p2/empty.txt new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MoveClassTest.java b/java/java-tests/testSrc/com/intellij/refactoring/MoveClassTest.java index c646301c664c..98c749655c2d 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/MoveClassTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/MoveClassTest.java @@ -89,6 +89,10 @@ public class MoveClassTest extends RefactoringTestCase { public void testUnusedImport() throws Exception { doTest("unusedImport", new String[]{"p2.F2"}, "p1"); } + + public void testQualifiedReferenceAfterFailedMethodConflictResolution() throws Exception { + doTest("qualifiedRef", new String[]{"p1.Test"}, "p2"); + } private void doTest(@NonNls String testName, @NonNls String[] classNames, @NonNls String newPackageName) throws Exception{ String root = JavaTestUtil.getJavaTestDataPath() + "/refactoring/moveClass/" + testName; From 2955a8cac7e8081a54d95a924459aaacf08ff78c Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Sun, 19 Jul 2015 14:45:14 +0300 Subject: [PATCH 102/106] NPE (IDEA-142788) --- .../sm/runner/ui/TestsPresentationUtil.java | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/TestsPresentationUtil.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/TestsPresentationUtil.java index e10bb3e87faa..44ff3ddc45b9 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/TestsPresentationUtil.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/TestsPresentationUtil.java @@ -219,23 +219,29 @@ public class TestsPresentationUtil { final SMTestProxy parent = testProxy.getParent(); final String name = testProxy.getName(); + if (name == null) { + return NO_NAME_TEST; + } + String presentationCandidate = name; if (parent != null) { String parentName = parent.getName(); - boolean parentStartsWith = name.startsWith(parentName); - if (!parentStartsWith && parent instanceof SMTestProxy.SMRootTestProxy) { - final String presentation = ((SMTestProxy.SMRootTestProxy)parent).getPresentation(); - if (presentation != null) { - parentName = presentation; - parentStartsWith = name.startsWith(parentName); + if (parentName != null) { + boolean parentStartsWith = name.startsWith(parentName); + if (!parentStartsWith && parent instanceof SMTestProxy.SMRootTestProxy) { + final String presentation = ((SMTestProxy.SMRootTestProxy)parent).getPresentation(); + if (presentation != null) { + parentName = presentation; + parentStartsWith = name.startsWith(parentName); + } } - } - if (parentStartsWith) { - presentationCandidate = name.substring(parentName.length()); - - // remove "." separator - if (presentationCandidate.startsWith(".")) { - presentationCandidate = presentationCandidate.substring(1); + if (parentStartsWith) { + presentationCandidate = name.substring(parentName.length()); + + // remove "." separator + if (presentationCandidate.startsWith(".")) { + presentationCandidate = presentationCandidate.substring(1); + } } } } From a94e79baffd97f86bbf5bc6ef08e9a4ae7e5a472 Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Sun, 19 Jul 2015 15:02:08 +0300 Subject: [PATCH 103/106] generate constructor: place varargs from base constructor as last parameter (IDEA-142811) --- .../generation/GenerateConstructorHandler.java | 11 +++++++++-- .../generateConstructor/afterBaseVarargs.java | 11 +++++++++++ .../generateConstructor/beforeBaseVarargs.java | 8 ++++++++ .../intellij/codeInsight/GenerateConstructorTest.java | 1 + 4 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 java/java-tests/testData/codeInsight/generateConstructor/afterBaseVarargs.java create mode 100644 java/java-tests/testData/codeInsight/generateConstructor/beforeBaseVarargs.java diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateConstructorHandler.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateConstructorHandler.java index 7990c5872b16..fd5a79fdb9db 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateConstructorHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateConstructorHandler.java @@ -270,8 +270,15 @@ public class GenerateConstructorHandler extends GenerateMembersHandlerBase { parm.getModifierList().addAfter(notNull, null); } - constructor.getParameterList().add(parm); - dummyConstructor.getParameterList().add(parm.copy()); + if (constructor.isVarArgs()) { + final PsiParameterList parameterList = constructor.getParameterList(); + parameterList.addBefore(parm, parameterList.getParameters()[parameterList.getParametersCount() - 1]); + final PsiParameterList dummyParameterlist = dummyConstructor.getParameterList(); + dummyParameterlist.addBefore(parm.copy(), dummyParameterlist.getParameters()[dummyParameterlist.getParametersCount() - 1]); + } else { + constructor.getParameterList().add(parm); + dummyConstructor.getParameterList().add(parm.copy()); + } fieldParams.add(parm); } diff --git a/java/java-tests/testData/codeInsight/generateConstructor/afterBaseVarargs.java b/java/java-tests/testData/codeInsight/generateConstructor/afterBaseVarargs.java new file mode 100644 index 000000000000..0e4a7e428de5 --- /dev/null +++ b/java/java-tests/testData/codeInsight/generateConstructor/afterBaseVarargs.java @@ -0,0 +1,11 @@ +class Base { + public Base(String... ignored) { } +} +class Derived extends Base { + int i; + + public Derived(int i, String... ignored) { + super(ignored); + this.i = i; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/generateConstructor/beforeBaseVarargs.java b/java/java-tests/testData/codeInsight/generateConstructor/beforeBaseVarargs.java new file mode 100644 index 000000000000..8fa940e99fe1 --- /dev/null +++ b/java/java-tests/testData/codeInsight/generateConstructor/beforeBaseVarargs.java @@ -0,0 +1,8 @@ +class Base { + public Base(String... ignored) { } +} +class Derived extends Base { + int i; + + +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateConstructorTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateConstructorTest.java index 6e626975d146..d94e980cebb1 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateConstructorTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateConstructorTest.java @@ -37,6 +37,7 @@ public class GenerateConstructorTest extends LightCodeInsightTestCase { public void testSameNamedFields() throws Exception { doTest(); } public void testEnumWithAbstractMethod() throws Exception { doTest(); } public void testNoMoreConstructorsCanBeGenerated() throws Exception { doTest(); } + public void testBaseVarargs() throws Exception { doTest(); } public void testImmediatelyAfterRBrace() throws Exception { // IDEADEV-28811 CodeStyleSettingsManager.getInstance(getProject()).getCurrentSettings().CLASS_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE; From fea3cf464343ef6bcc76fa97ad14afb61e462757 Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Mon, 20 Jul 2015 14:08:39 +0300 Subject: [PATCH 104/106] sm protocol: replace collection of listeners with message bus --- .../sm/SMTestRunnerConnectionUtil.java | 9 +- ...eralIdBasedToSMTRunnerEventsConvertor.java | 121 +++------------- .../sm/runner/GeneralTestEventsProcessor.java | 24 +++- .../GeneralToSMTRunnerEventsConvertor.java | 136 +++--------------- .../sm/runner/SMTRunnerEventsListener.java | 3 + ...IdBasedToSMTRunnerEventsConvertorTest.java | 2 +- ...GeneralToSMTRunnerEventsConvertorTest.java | 2 +- ...MockGeneralTestEventsProcessorAdapter.java | 7 +- ...tputToGeneralTestsEventsConverterTest.java | 2 +- .../sm/runner/SMTRunnerConsoleTest.java | 2 +- .../ui/SMTestRunnerResultsFormTest.java | 2 +- 11 files changed, 81 insertions(+), 229 deletions(-) diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/SMTestRunnerConnectionUtil.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/SMTestRunnerConnectionUtil.java index dab4546b71b2..6775dc34f4c8 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/SMTestRunnerConnectionUtil.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/SMTestRunnerConnectionUtil.java @@ -26,7 +26,10 @@ import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.execution.testframework.sm.runner.*; -import com.intellij.execution.testframework.sm.runner.ui.*; +import com.intellij.execution.testframework.sm.runner.ui.AttachToProcessListener; +import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerConsoleView; +import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerUIActionsHandler; +import com.intellij.execution.testframework.sm.runner.ui.SMTestRunnerResultsForm; import com.intellij.execution.testframework.sm.runner.ui.statistics.StatisticsPanel; import com.intellij.execution.testframework.ui.BaseTestsOutputConsoleView; import com.intellij.execution.ui.ConsoleView; @@ -186,10 +189,10 @@ public class SMTestRunnerConnectionUtil { // events processor final GeneralTestEventsProcessor eventsProcessor; if (idBasedTestTree) { - eventsProcessor = new GeneralIdBasedToSMTRunnerEventsConvertor(resultsViewer.getTestsRootNode(), testFrameworkName); + eventsProcessor = new GeneralIdBasedToSMTRunnerEventsConvertor(consoleProperties.getProject(), resultsViewer.getTestsRootNode(), testFrameworkName); } else { - eventsProcessor = new GeneralToSMTRunnerEventsConvertor(resultsViewer.getTestsRootNode(), testFrameworkName); + eventsProcessor = new GeneralToSMTRunnerEventsConvertor(consoleProperties.getProject(), resultsViewer.getTestsRootNode(), testFrameworkName); } if (locator != null) { diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java index 2bc10fced23a..8bbc142975c8 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java @@ -22,6 +22,7 @@ import com.intellij.execution.testframework.sm.runner.events.*; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.util.containers.ContainerUtil; import gnu.trove.TIntObjectHashMap; @@ -36,7 +37,6 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP private final TIntObjectHashMap myNodeByIdMap = new TIntObjectHashMap(); private final Set myRunningTestNodes = ContainerUtil.newHashSet(); - private final List myEventsListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private final SMTestProxy.SMRootTestProxy myTestsRootProxy; private final Node myTestsRootNode; private final String myTestFrameworkName; @@ -45,7 +45,10 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP private SMTestLocator myLocator = null; private TestProxyPrinterProvider myTestProxyPrinterProvider = null; - public GeneralIdBasedToSMTRunnerEventsConvertor(@NotNull SMTestProxy.SMRootTestProxy testsRootProxy, @NotNull String testFrameworkName) { + public GeneralIdBasedToSMTRunnerEventsConvertor(Project project, + @NotNull SMTestProxy.SMRootTestProxy testsRootProxy, + @NotNull String testFrameworkName) { + super(project); myTestsRootProxy = testsRootProxy; myTestsRootNode = new Node(0, null, testsRootProxy); myTestFrameworkName = testFrameworkName; @@ -57,16 +60,12 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP myLocator = locator; } - public void addEventsListener(@NotNull SMTRunnerEventsListener listener) { - myEventsListeners.add(listener); - } - public void onStartTesting() { addToInvokeLater(new Runnable() { public void run() { myTestsRootNode.setState(State.RUNNING, GeneralIdBasedToSMTRunnerEventsConvertor.this); myTestsRootProxy.setStarted(); - fireOnTestingStarted(); + myEventPublisher.onTestingStarted(myTestsRootProxy); } }); } @@ -105,7 +104,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP myNodeByIdMap.clear(); myRunningTestNodes.clear(); - fireOnTestingFinished(); + myEventPublisher.onTestingFinished(myTestsRootProxy); } }); stopEventProcessing(); @@ -201,7 +200,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP SMTestProxy testProxy = node.getProxy(); testProxy.setDuration(testFinishedEvent.getDuration()); testProxy.setFinished(); - fireOnTestFinished(testProxy); + myEventPublisher.onTestFinished(testProxy); terminateNode(node, State.FINISHED); } } @@ -215,7 +214,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP if (node != null) { SMTestProxy suiteProxy = node.getProxy(); suiteProxy.setFinished(); - fireOnSuiteFinished(suiteProxy); + myEventPublisher.onSuiteFinished(suiteProxy); terminateNode(node, State.FINISHED); } } @@ -264,7 +263,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP final int testCount) { addToInvokeLater(new Runnable() { public void run() { - fireOnCustomProgressTestsCategory(categoryName, testCount); + myEventPublisher.onCustomProgressTestsCategory(categoryName, testCount); } }); } @@ -272,7 +271,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP public void onCustomProgressTestStarted() { addToInvokeLater(new Runnable() { public void run() { - fireOnCustomProgressTestStarted(); + myEventPublisher.onCustomProgressTestStarted(); } }); } @@ -281,7 +280,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP public void onCustomProgressTestFinished() { addToInvokeLater(new Runnable() { public void run() { - fireOnCustomProgressTestFinished(); + myEventPublisher.onCustomProgressTestFinished(); } }); } @@ -289,7 +288,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP public void onCustomProgressTestFailed() { addToInvokeLater(new Runnable() { public void run() { - fireOnCustomProgressTestFailed(); + myEventPublisher.onCustomProgressTestFailed(); } }); } @@ -326,7 +325,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP } // fire event - fireOnTestFailed(testProxy); + myEventPublisher.onTestFailed(testProxy); terminateNode(node, State.FAILED); } @@ -341,7 +340,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP SMTestProxy testProxy = node.getProxy(); testProxy.setTestIgnored(testIgnoredEvent.getIgnoreComment(), testIgnoredEvent.getStacktrace()); // fire event - fireOnTestIgnored(testProxy); + myEventPublisher.onTestIgnored(testProxy); terminateNode(node, State.IGNORED); } } @@ -370,7 +369,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP public void onTestsCountInSuite(final int count) { addToInvokeLater(new Runnable() { public void run() { - fireOnTestsCountInSuite(count); + myEventPublisher.onTestsCountInSuite(count); } }); } @@ -397,87 +396,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP Node node = myNodeByIdMap.get(id); return node != null ? node.getProxy() : null; } - - private void fireOnTestingStarted() { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestingStarted(myTestsRootProxy); - } - } - - private void fireOnTestingFinished() { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestingFinished(myTestsRootProxy); - } - } - - private void fireOnTestsCountInSuite(final int count) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestsCountInSuite(count); - } - } - - - private void fireOnTestStarted(final SMTestProxy test) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestStarted(test); - } - } - - private void fireOnTestFinished(final SMTestProxy test) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestFinished(test); - } - } - - private void fireOnTestFailed(final SMTestProxy test) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestFailed(test); - } - } - - private void fireOnTestIgnored(final SMTestProxy test) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestIgnored(test); - } - } - - private void fireOnSuiteStarted(final SMTestProxy suite) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onSuiteStarted(suite); - } - } - - private void fireOnSuiteFinished(final SMTestProxy suite) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onSuiteFinished(suite); - } - } - - - private void fireOnCustomProgressTestsCategory(@Nullable final String categoryName, int testCount) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onCustomProgressTestsCategory(categoryName, testCount); - } - } - - private void fireOnCustomProgressTestStarted() { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onCustomProgressTestStarted(); - } - } - - private void fireOnCustomProgressTestFinished() { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onCustomProgressTestFinished(); - } - } - - private void fireOnCustomProgressTestFailed() { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onCustomProgressTestFailed(); - } - } - + /* * Remove listeners, etc */ @@ -485,7 +404,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP super.dispose(); addToInvokeLater(new Runnable() { public void run() { - myEventsListeners.clear(); + disconnectListeners(); if (!myRunningTestNodes.isEmpty()) { Application application = ApplicationManager.getApplication(); @@ -506,10 +425,10 @@ public class GeneralIdBasedToSMTRunnerEventsConvertor extends GeneralTestEventsP SMTestProxy proxy = node.getProxy(); proxy.setStarted(); if (proxy.isSuite()) { - fireOnSuiteStarted(proxy); + myEventPublisher.onSuiteStarted(proxy); } else { myRunningTestNodes.add(lowestNode); - fireOnTestStarted(proxy); + myEventPublisher.onTestStarted(proxy); } node = node.getParentNode(); } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java index fdeaf362cd96..482dec299485 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralTestEventsProcessor.java @@ -19,11 +19,14 @@ import com.intellij.execution.testframework.sm.runner.events.*; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.Key; import com.intellij.util.Processor; +import com.intellij.util.containers.HashMap; import com.intellij.util.containers.TransferToEDTQueue; +import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -31,7 +34,6 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Collection; import java.util.List; -import java.util.Map; /** * Processes events of test runner in general text-based form. @@ -41,6 +43,8 @@ import java.util.Map; * @author: Roman Chernyatchik */ public abstract class GeneralTestEventsProcessor implements Disposable { + protected final SMTRunnerEventsListener myEventPublisher; + private final Project myProject; private TransferToEDTQueue myTransferToEDTQueue = new TransferToEDTQueue("SM queue", new Processor() { @Override @@ -49,8 +53,12 @@ public abstract class GeneralTestEventsProcessor implements Disposable { return true; } }, getDisposedCondition(), 300); + private HashMap myListenerAdapters = new HashMap(); - + public GeneralTestEventsProcessor(Project project) { + myProject = project; + myEventPublisher = project.getMessageBus().syncPublisher(SMTRunnerEventsListener.TEST_STATUS); + } // tree construction events public void onRootPresentationAdded(String rootName, String comment, String rootLocation) {} @@ -108,7 +116,11 @@ public abstract class GeneralTestEventsProcessor implements Disposable { public abstract void setLocator(@NotNull SMTestLocator locator); - public abstract void addEventsListener(@NotNull SMTRunnerEventsListener viewer); + public void addEventsListener(@NotNull SMTRunnerEventsListener listener) { + final MessageBusConnection connection = myProject.getMessageBus().connect(); + myListenerAdapters.put(listener, connection); + connection.subscribe(SMTRunnerEventsListener.TEST_STATUS, listener); + } public abstract void setPrinterProvider(@NotNull TestProxyPrinterProvider printerProvider); @@ -124,6 +136,12 @@ public abstract class GeneralTestEventsProcessor implements Disposable { } } + protected void disconnectListeners() { + for (MessageBusConnection connection : myListenerAdapters.values()) { + connection.disconnect(); + } + } + public Condition getDisposedCondition() { return Conditions.alwaysFalse(); } diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java index 9a26086f64ee..8cd45b387ec1 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java @@ -18,15 +18,13 @@ package com.intellij.execution.testframework.sm.runner; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.execution.testframework.AbstractTestProxy; import com.intellij.execution.testframework.sm.SMTestRunnerConnectionUtil; -import com.intellij.execution.testframework.sm.SMTestsRunnerBundle; import com.intellij.execution.testframework.sm.runner.events.*; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ObjectUtils; -import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; @@ -44,7 +42,6 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso private final Map myRunningTestsFullNameToProxy = new HashMap(); private final Set myFailedTestsSet = new HashSet(); private final TestSuiteStack mySuitesStack = new TestSuiteStack(); - private final List myEventsListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private final SMTestProxy.SMRootTestProxy myTestsRootNode; private final String myTestFrameworkName; @@ -52,7 +49,9 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso private SMTestLocator myLocator = null; private boolean myTreeBuildBeforeStart = false; - public GeneralToSMTRunnerEventsConvertor(@NotNull SMTestProxy.SMRootTestProxy testsRootNode, @NotNull String testFrameworkName) { + public GeneralToSMTRunnerEventsConvertor(Project project, @NotNull SMTestProxy.SMRootTestProxy testsRootNode, + @NotNull String testFrameworkName) { + super(project); myTestsRootNode = testsRootNode; myTestFrameworkName = testFrameworkName; } @@ -62,10 +61,6 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso myLocator = locator; } - public void addEventsListener(@NotNull final SMTRunnerEventsListener listener) { - myEventsListeners.add(listener); - } - public void onStartTesting() { addToInvokeLater(new Runnable() { public void run() { @@ -73,7 +68,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso myTestsRootNode.setStarted(); //fire - fireOnTestingStarted(); + myEventPublisher.onTestingStarted(myTestsRootNode); } }); } @@ -109,7 +104,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso //fire events - fireOnTestingFinished(); + myEventPublisher.onTestingFinished(myTestsRootNode); } }); stopEventProcessing(); @@ -141,7 +136,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso testProxy.setLocator(myLocator); } getCurrentSuite().addChild(testProxy); - fireOnSuiteTreeNodeAdded(testProxy); + myEventPublisher.onSuiteTreeNodeAdded(testProxy); } }); } @@ -161,7 +156,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso mySuitesStack.pushSuite(newSuite); - fireOnSuiteTreeStarted(newSuite); + myEventPublisher.onSuiteTreeStarted(newSuite); } }); } @@ -217,7 +212,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso testProxy.setStarted(); //fire events - fireOnTestStarted(testProxy); + myEventPublisher.onTestStarted(testProxy); } }); } @@ -247,7 +242,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso newSuite.setStarted(); //fire event - fireOnSuiteStarted(newSuite); + myEventPublisher.onSuiteStarted(newSuite); } }); } @@ -282,7 +277,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso myRunningTestsFullNameToProxy.remove(fullTestName); //fire events - fireOnTestFinished(testProxy); + myEventPublisher.onTestFinished(testProxy); } }); } @@ -296,7 +291,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso mySuite.setFinished(); //fire events - fireOnSuiteFinished(mySuite); + myEventPublisher.onSuiteFinished(mySuite); } } }); @@ -333,7 +328,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso final int testCount) { addToInvokeLater(new Runnable() { public void run() { - fireOnCustomProgressTestsCategory(categoryName, testCount); + myEventPublisher.onCustomProgressTestsCategory(categoryName, testCount); } }); } @@ -341,7 +336,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso public void onCustomProgressTestStarted() { addToInvokeLater(new Runnable() { public void run() { - fireOnCustomProgressTestStarted(); + myEventPublisher.onCustomProgressTestStarted(); } }); } @@ -349,7 +344,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso public void onCustomProgressTestFinished() { addToInvokeLater(new Runnable() { public void run() { - fireOnCustomProgressTestFinished(); + myEventPublisher.onCustomProgressTestFinished(); } }); } @@ -358,7 +353,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso public void onCustomProgressTestFailed() { addToInvokeLater(new Runnable() { public void run() { - fireOnCustomProgressTestFailed(); + myEventPublisher.onCustomProgressTestFailed(); } }); } @@ -428,7 +423,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso myFailedTestsSet.add(testProxy); // fire event - fireOnTestFailed(testProxy); + myEventPublisher.onTestFailed(testProxy); } }); } @@ -465,7 +460,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso testProxy.setTestIgnored(ignoreComment, stackTrace); // fire event - fireOnTestIgnored(testProxy); + myEventPublisher.onTestIgnored(testProxy); } }); } @@ -498,7 +493,7 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso public void onTestsCountInSuite(final int count) { addToInvokeLater(new Runnable() { public void run() { - fireOnTestsCountInSuite(count); + myEventPublisher.onTestsCountInSuite(count); } }); } @@ -557,97 +552,6 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso return namesDump; } - private void fireOnTestingStarted() { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestingStarted(myTestsRootNode); - } - } - - private void fireOnTestingFinished() { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestingFinished(myTestsRootNode); - } - } - - private void fireOnTestsCountInSuite(final int count) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestsCountInSuite(count); - } - } - - private void fireOnSuiteTreeNodeAdded(SMTestProxy testProxy) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onSuiteTreeNodeAdded(testProxy); - } - } - - private void fireOnSuiteTreeStarted(SMTestProxy suite) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onSuiteTreeStarted(suite); - } - } - - - private void fireOnTestStarted(final SMTestProxy test) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestStarted(test); - } - } - - private void fireOnTestFinished(final SMTestProxy test) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestFinished(test); - } - } - - private void fireOnTestFailed(final SMTestProxy test) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestFailed(test); - } - } - - private void fireOnTestIgnored(final SMTestProxy test) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onTestIgnored(test); - } - } - - private void fireOnSuiteStarted(final SMTestProxy suite) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onSuiteStarted(suite); - } - } - - private void fireOnSuiteFinished(final SMTestProxy suite) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onSuiteFinished(suite); - } - } - - - private void fireOnCustomProgressTestsCategory(@Nullable final String categoryName, int testCount) { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onCustomProgressTestsCategory(categoryName, testCount); - } - } - - private void fireOnCustomProgressTestStarted() { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onCustomProgressTestStarted(); - } - } - - private void fireOnCustomProgressTestFinished() { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onCustomProgressTestFinished(); - } - } - - private void fireOnCustomProgressTestFailed() { - for (SMTRunnerEventsListener listener : myEventsListeners) { - listener.onCustomProgressTestFailed(); - } - } /* * Remove listeners, etc @@ -656,8 +560,8 @@ public class GeneralToSMTRunnerEventsConvertor extends GeneralTestEventsProcesso super.dispose(); addToInvokeLater(new Runnable() { public void run() { - myEventsListeners.clear(); + disconnectListeners(); if (!myRunningTestsFullNameToProxy.isEmpty()) { final Application application = ApplicationManager.getApplication(); if (!application.isHeadlessEnvironment() && !application.isUnitTestMode()) { diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerEventsListener.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerEventsListener.java index 1c0a8231b1df..20a03b89f341 100644 --- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerEventsListener.java +++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/SMTRunnerEventsListener.java @@ -15,6 +15,7 @@ */ package com.intellij.execution.testframework.sm.runner; +import com.intellij.util.messages.Topic; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -26,6 +27,8 @@ import java.util.List; * Handles Test Runner events */ public interface SMTRunnerEventsListener { + Topic TEST_STATUS = new Topic("test status", SMTRunnerEventsListener.class); + /** * On start testing, before tests and suits launching * @param testsRoot diff --git a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertorTest.java b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertorTest.java index e0eddc09b09f..d1066a7c1aca 100644 --- a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertorTest.java +++ b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertorTest.java @@ -28,7 +28,7 @@ public class GeneralIdBasedToSMTRunnerEventsConvertorTest extends BaseSMTRunnerT protected void setUp() throws Exception { super.setUp(); myRootProxy = new SMTestProxy.SMRootTestProxy(); - myEventsProcessor = new GeneralIdBasedToSMTRunnerEventsConvertor(myRootProxy, "test"); + myEventsProcessor = new GeneralIdBasedToSMTRunnerEventsConvertor(getProject(), myRootProxy, "test"); myEventsProcessor.onStartTesting(); } diff --git a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertorTest.java b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertorTest.java index 2ce9b1695713..90b8559b7f42 100644 --- a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertorTest.java +++ b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertorTest.java @@ -83,7 +83,7 @@ public class GeneralToSMTRunnerEventsConvertorTest extends BaseSMTRunnerTestCase myConsole = new MyConsoleView(consoleProperties, environment); myConsole.initUI(); myResultsViewer = myConsole.getResultsViewer(); - myEventsProcessor = new GeneralToSMTRunnerEventsConvertor(myResultsViewer.getTestsRootNode(), "SMTestFramework"); + myEventsProcessor = new GeneralToSMTRunnerEventsConvertor(consoleProperties.getProject(), myResultsViewer.getTestsRootNode(), "SMTestFramework"); myEventsProcessor.addEventsListener(myResultsViewer); myTreeModel = myResultsViewer.getTreeView().getModel(); diff --git a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/MockGeneralTestEventsProcessorAdapter.java b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/MockGeneralTestEventsProcessorAdapter.java index 11a25410cfe7..0b3da9a09fde 100644 --- a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/MockGeneralTestEventsProcessorAdapter.java +++ b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/MockGeneralTestEventsProcessorAdapter.java @@ -16,6 +16,7 @@ package com.intellij.execution.testframework.sm.runner; import com.intellij.execution.testframework.sm.runner.events.*; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -26,6 +27,10 @@ import org.jetbrains.annotations.Nullable; public class MockGeneralTestEventsProcessorAdapter extends GeneralTestEventsProcessor { private final StringBuilder myOutputBuffer = new StringBuilder(); + public MockGeneralTestEventsProcessorAdapter(Project project) { + super(project); + } + @Override public void onStartTesting() { } @@ -96,7 +101,7 @@ public class MockGeneralTestEventsProcessorAdapter extends GeneralTestEventsProc } @Override - public void addEventsListener(@NotNull SMTRunnerEventsListener viewer) { + public void addEventsListener(@NotNull SMTRunnerEventsListener listener) { } @Override diff --git a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/OutputToGeneralTestsEventsConverterTest.java b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/OutputToGeneralTestsEventsConverterTest.java index 2fafd4957935..acc90a0131ae 100644 --- a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/OutputToGeneralTestsEventsConverterTest.java +++ b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/OutputToGeneralTestsEventsConverterTest.java @@ -38,7 +38,7 @@ public class OutputToGeneralTestsEventsConverterTest extends BaseSMTRunnerTestCa testFrameworkName, DefaultRunExecutor.getRunExecutorInstance()); myOutputConsumer = new OutputToGeneralTestEventsConverter(testFrameworkName, properties); - myEnventsProcessor = new MockGeneralTestEventsProcessorAdapter(); + myEnventsProcessor = new MockGeneralTestEventsProcessorAdapter(properties.getProject()); myOutputConsumer.setProcessor(myEnventsProcessor); } diff --git a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/SMTRunnerConsoleTest.java b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/SMTRunnerConsoleTest.java index 3e03256428ec..2d58845ae008 100644 --- a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/SMTRunnerConsoleTest.java +++ b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/SMTRunnerConsoleTest.java @@ -71,7 +71,7 @@ public class SMTRunnerConsoleTest extends BaseSMTRunnerTestCase { myConsole.initUI(); myResultsViewer = myConsole.getResultsViewer(); myRootSuite = myResultsViewer.getTestsRootNode(); - myEventsProcessor = new GeneralToSMTRunnerEventsConvertor(myResultsViewer.getTestsRootNode(), "SMTestFramework"); + myEventsProcessor = new GeneralToSMTRunnerEventsConvertor(consoleProperties.getProject(), myResultsViewer.getTestsRootNode(), "SMTestFramework"); myEventsProcessor.onStartTesting(); } diff --git a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsFormTest.java b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsFormTest.java index 8458f7132a62..e6a16bb04ec7 100644 --- a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsFormTest.java +++ b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsFormTest.java @@ -61,7 +61,7 @@ public class SMTestRunnerResultsFormTest extends BaseSMTRunnerTestCase { myConsole.initUI(); myResultsViewer = myConsole.getResultsViewer(); myTestsRootNode = myResultsViewer.getTestsRootNode(); - myEventsProcessor = new GeneralToSMTRunnerEventsConvertor(myResultsViewer.getTestsRootNode(), "SMTestFramework"); + myEventsProcessor = new GeneralToSMTRunnerEventsConvertor(myConsoleProperties.getProject(), myResultsViewer.getTestsRootNode(), "SMTestFramework"); myEventsProcessor.addEventsListener(myResultsViewer); myTreeModel = myResultsViewer.getTreeView().getModel(); } From af596a12d58869f12e597d11078b359bc75261df Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Mon, 20 Jul 2015 14:55:24 +0300 Subject: [PATCH 105/106] testng: disable javadoc check for new testng versions --- .../testng/src/com/theoryinpractice/testng/util/TestNGUtil.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java b/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java index 9b3d84080df8..2ed37f25b220 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java +++ b/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java @@ -69,7 +69,7 @@ public class TestNGUtil { private static boolean hasDocTagsSupport() { String testngJarPath = PathUtil.getJarPathForClass(Test.class); String version = JarUtil.getJarAttribute(new File(testngJarPath), Attributes.Name.IMPLEMENTATION_VERSION); - return version == null || StringUtil.compareVersionNumbers(version, "5.12") <= 0; + return version != null && StringUtil.compareVersionNumbers(version, "5.12") <= 0; } public static final String TEST_ANNOTATION_FQN = Test.class.getName(); From 16994effc304e009d8bcbfd10fa2db8207873f3b Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Mon, 20 Jul 2015 15:12:30 +0300 Subject: [PATCH 106/106] test discovery: process collected traces during test run --- .../JavaTestFrameworkRunnableState.java | 8 +- .../testDiscovery/TestDiscoveryExtension.java | 78 +++++++++++++------ .../testframework/sm/runner/SMTestProxy.java | 19 +++++ .../testframework/TestProxyRoot.java | 4 + 4 files changed, 85 insertions(+), 24 deletions(-) diff --git a/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkRunnableState.java b/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkRunnableState.java index 48acde80c94a..27a063e8f8d2 100644 --- a/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkRunnableState.java +++ b/java/execution/impl/src/com/intellij/execution/JavaTestFrameworkRunnableState.java @@ -117,11 +117,15 @@ public abstract class JavaTestFrameworkRunnableState