diff options
Diffstat (limited to 'platform/lang-impl')
128 files changed, 1950 insertions, 1929 deletions
diff --git a/platform/lang-impl/src/com/intellij/application/options/CodeStyleSchemesConfigurable.java b/platform/lang-impl/src/com/intellij/application/options/CodeStyleSchemesConfigurable.java index 9f38c6605f11..b07c7a62bc47 100644 --- a/platform/lang-impl/src/com/intellij/application/options/CodeStyleSchemesConfigurable.java +++ b/platform/lang-impl/src/com/intellij/application/options/CodeStyleSchemesConfigurable.java @@ -23,6 +23,7 @@ import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.registry.Registry; import com.intellij.psi.codeStyle.CodeStyleScheme; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsProvider; @@ -55,6 +56,9 @@ public class CodeStyleSchemesConfigurable extends SearchableConfigurable.Parent. public JComponent createComponent() { myModel = ensureModel(); + if (Registry.is("ide.file.settings.order.new")) { + return myPanels == null || myPanels.isEmpty() ? null : myPanels.get(0).createComponent(); + } return myRootSchemesPanel.getPanel(); } @@ -232,6 +236,14 @@ public class CodeStyleSchemesConfigurable extends SearchableConfigurable.Parent. } } + if (Registry.is("ide.file.settings.order.new")) { + int size = myPanels.size(); + Configurable[] result = new Configurable[size > 0 ? size - 1 : 0]; + for (int i = 0; i < result.length; i++) { + result[i] = myPanels.get(i + 1); + } + return result; + } return myPanels.toArray(new Configurable[myPanels.size()]); } @@ -255,7 +267,7 @@ public class CodeStyleSchemesConfigurable extends SearchableConfigurable.Parent. @Override public void currentSettingsChanged() { - + } @Override diff --git a/platform/lang-impl/src/com/intellij/application/options/GeneralCodeStylePanel.java b/platform/lang-impl/src/com/intellij/application/options/GeneralCodeStylePanel.java index d51ddbd827d5..e3dabad85b21 100644 --- a/platform/lang-impl/src/com/intellij/application/options/GeneralCodeStylePanel.java +++ b/platform/lang-impl/src/com/intellij/application/options/GeneralCodeStylePanel.java @@ -111,7 +111,7 @@ public class GeneralCodeStylePanel extends CodeStyleAbstractPanel { myLineSeparatorCombo.addItem(MACINTOSH_STRING); addPanelToWatch(myPanel); - myRightMarginSpinner.setModel(new SpinnerNumberModel(settings.RIGHT_MARGIN, 1, 1000000, 1)); + myRightMarginSpinner.setModel(new SpinnerNumberModel(settings.getDefaultRightMargin(), 1, 1000000, 1)); myIndentOptionsEditor = new SmartIndentOptionsEditor(); myDefaultIndentOptionsPanel.add(myIndentOptionsEditor.createPanel(), BorderLayout.CENTER); @@ -165,7 +165,7 @@ public class GeneralCodeStylePanel extends CodeStyleAbstractPanel { public void apply(CodeStyleSettings settings) { settings.LINE_SEPARATOR = getSelectedLineSeparator(); - settings.RIGHT_MARGIN = ((Number) myRightMarginSpinner.getValue()).intValue(); + settings.setDefaultRightMargin(((Number) myRightMarginSpinner.getValue()).intValue()); settings.WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN = myCbWrapWhenTypingReachesRightMargin.isSelected(); myIndentOptionsEditor.setEnabled(true); myIndentOptionsEditor.apply(settings, settings.OTHER_INDENT_OPTIONS); @@ -226,7 +226,7 @@ public class GeneralCodeStylePanel extends CodeStyleAbstractPanel { return true; } - if (!Comparing.equal(myRightMarginSpinner.getValue(), settings.RIGHT_MARGIN)) return true; + if (!Comparing.equal(myRightMarginSpinner.getValue(), settings.getDefaultRightMargin())) return true; myIndentOptionsEditor.setEnabled(true); if (myEnableFormatterTags.isSelected()) { @@ -265,7 +265,7 @@ public class GeneralCodeStylePanel extends CodeStyleAbstractPanel { myLineSeparatorCombo.setSelectedItem(SYSTEM_DEPENDANT_STRING); } - myRightMarginSpinner.setValue(settings.RIGHT_MARGIN); + myRightMarginSpinner.setValue(settings.getDefaultRightMargin()); myCbWrapWhenTypingReachesRightMargin.setSelected(settings.WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN); myIndentOptionsEditor.reset(settings, settings.OTHER_INDENT_OPTIONS); myIndentOptionsEditor.setEnabled(true); diff --git a/platform/lang-impl/src/com/intellij/application/options/OtherTabsAndIndentsPanel.java b/platform/lang-impl/src/com/intellij/application/options/OtherTabsAndIndentsPanel.java index cf118835aa0e..aadc34a0ac1f 100644 --- a/platform/lang-impl/src/com/intellij/application/options/OtherTabsAndIndentsPanel.java +++ b/platform/lang-impl/src/com/intellij/application/options/OtherTabsAndIndentsPanel.java @@ -91,7 +91,7 @@ public class OtherTabsAndIndentsPanel extends CodeStyleAbstractPanel { installPreviewPanel(myPreviewPanel); addPanelToWatch(myPanel); - myRightMargin = settings.RIGHT_MARGIN; + myRightMargin = settings.getDefaultRightMargin(); } diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/RightMarginForm.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/RightMarginForm.java index 70c747dc11ca..0759052ee623 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/RightMarginForm.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/RightMarginForm.java @@ -48,7 +48,7 @@ public class RightMarginForm { public RightMarginForm(@NotNull Language language, @NotNull CodeStyleSettings settings) { myLanguage = language; - myDefaultRightMargin = settings.RIGHT_MARGIN; + myDefaultRightMargin = settings.getDefaultRightMargin(); myDefaultGeneralCheckBox.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { @@ -71,7 +71,7 @@ public class RightMarginForm { } else { myDefaultGeneralCheckBox.setSelected(true); - myRightMarginField.setText(Integer.toString(settings.RIGHT_MARGIN)); + myRightMarginField.setText(Integer.toString(settings.getDefaultRightMargin())); if (langSettings == settings) { myDefaultGeneralCheckBox.setEnabled(false); myRightMarginField.setEnabled(false); @@ -86,7 +86,7 @@ public class RightMarginForm { langSettings.RIGHT_MARGIN = -1; } else { - langSettings.RIGHT_MARGIN = getFieldRightMargin(settings.RIGHT_MARGIN); + langSettings.RIGHT_MARGIN = getFieldRightMargin(settings.getDefaultRightMargin()); } } } @@ -97,7 +97,7 @@ public class RightMarginForm { return langSettings.RIGHT_MARGIN >= 0; } else { - return langSettings.RIGHT_MARGIN != getFieldRightMargin(settings.RIGHT_MARGIN); + return langSettings.RIGHT_MARGIN != getFieldRightMargin(settings.getDefaultRightMargin()); } } diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/ColorAndFontOptions.java b/platform/lang-impl/src/com/intellij/application/options/colors/ColorAndFontOptions.java index 5e3017206132..ce2a00d3d671 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/ColorAndFontOptions.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/ColorAndFontOptions.java @@ -81,6 +81,8 @@ import java.util.*; import java.util.List; public class ColorAndFontOptions extends SearchableConfigurable.Parent.Abstract implements EditorOptionsProvider { + public static final String ID = "reference.settingsdialog.IDE.editor.colors"; + private HashMap<String,MyColorScheme> mySchemes; private MyColorScheme mySelectedScheme; public static final String DIFF_GROUP = ApplicationBundle.message("title.diff"); @@ -999,7 +1001,7 @@ public class ColorAndFontOptions extends SearchableConfigurable.Parent.Abstract @Override @NotNull public String getHelpTopic() { - return "reference.settingsdialog.IDE.editor.colors"; + return ID; } private static class MyColorScheme extends EditorColorsSchemeImpl { diff --git a/platform/lang-impl/src/com/intellij/application/options/editor/EditorTabsConfigurable.form b/platform/lang-impl/src/com/intellij/application/options/editor/EditorTabsConfigurable.form index db23ce17b2c3..edb9fcdb9e18 100644 --- a/platform/lang-impl/src/com/intellij/application/options/editor/EditorTabsConfigurable.form +++ b/platform/lang-impl/src/com/intellij/application/options/editor/EditorTabsConfigurable.form @@ -3,12 +3,12 @@ <grid id="27dc6" binding="myRootPanel" layout-manager="GridLayoutManager" row-count="3" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> <margin top="0" left="0" bottom="0" right="0"/> <constraints> - <xy x="20" y="20" width="500" height="585"/> + <xy x="20" y="20" width="500" height="614"/> </constraints> <properties/> <border type="none"/> <children> - <grid id="ed507" layout-manager="GridLayoutManager" row-count="7" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> + <grid id="ed507" layout-manager="GridLayoutManager" row-count="8" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> <margin top="0" left="0" bottom="0" right="0"/> <constraints> <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="9" fill="3" indent="0" use-parent-layout="false"/> @@ -101,6 +101,35 @@ <text resource-bundle="messages/ApplicationBundle" key="checkbox.show.tabs.tooltips"/> </properties> </component> + <grid id="e3283" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> + <margin top="0" left="0" bottom="0" right="0"/> + <constraints> + <grid row="7" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/> + </constraints> + <properties/> + <border type="none"/> + <children> + <component id="2479d" class="javax.swing.JLabel"> + <constraints> + <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0" indent="0" use-parent-layout="false"/> + </constraints> + <properties> + <text resource-bundle="messages/ApplicationBundle" key="editbox.tab.title.limit"/> + </properties> + </component> + <component id="3499c" class="javax.swing.JTextField" binding="myTabTitleLimitField"> + <constraints> + <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="8" fill="0" indent="0" use-parent-layout="false"> + <preferred-size width="30" height="27"/> + </grid> + </constraints> + <properties> + <columns value="2"/> + <text value="30"/> + </properties> + </component> + </children> + </grid> </children> </grid> <vspacer id="651b4"> @@ -119,7 +148,7 @@ </clientProperties> <border type="none" title-resource-bundle="messages/ApplicationBundle" title-key="group.tab.closing.policy"/> <children> - <grid id="5a5a7" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> + <grid id="5a5a7" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> <margin top="0" left="0" bottom="0" right="0"/> <constraints> <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/> @@ -147,25 +176,6 @@ <text value="15"/> </properties> </component> - <component id="2479d" class="javax.swing.JLabel"> - <constraints> - <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0" indent="0" use-parent-layout="false"/> - </constraints> - <properties> - <text resource-bundle="messages/ApplicationBundle" key="editbox.tab.title.limit"/> - </properties> - </component> - <component id="3499c" class="javax.swing.JTextField" binding="myTabTitleLimitField"> - <constraints> - <grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="8" fill="0" indent="0" use-parent-layout="false"> - <preferred-size width="30" height="27"/> - </grid> - </constraints> - <properties> - <columns value="2"/> - <text value="30"/> - </properties> - </component> </children> </grid> <grid id="9b723" layout-manager="GridLayoutManager" row-count="3" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="2"> diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/FormatChangedTextUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/FormatChangedTextUtil.java index af6bbdc931ca..0bc36c17325d 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/actions/FormatChangedTextUtil.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/FormatChangedTextUtil.java @@ -312,8 +312,8 @@ public class FormatChangedTextUtil { List<TextRange> ranges = ContainerUtil.newArrayList(); for (Range range : changedRanges) { if (range.getType() != Range.DELETED) { - int changeStartLine = range.getOffset1(); - int changeEndLine = range.getOffset2(); + int changeStartLine = range.getLine1(); + int changeEndLine = range.getLine2(); int lineStartOffset = document.getLineStartOffset(changeStartLine); int lineEndOffset = document.getLineEndOffset(changeEndLine - 1); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonListeners.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonListeners.java index 75a4fd410959..c8d5ec4b8ddb 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonListeners.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonListeners.java @@ -104,7 +104,7 @@ public class DaemonListeners implements Disposable { private final ProjectLevelVcsManager myProjectLevelVcsManager; private final VcsDirtyScopeManager myVcsDirtyScopeManager; private final FileStatusManager myFileStatusManager; - private final ActionManager myActionManager; + @NotNull private final ActionManager myActionManager; private final TooltipController myTooltipController; private boolean myEscPressed; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HectorComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HectorComponent.java index 0483d5a05027..825e72bc98e6 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HectorComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HectorComponent.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -91,7 +91,7 @@ public class HectorComponent extends JPanel { Collections.sort(languages, PsiUtilBase.LANGUAGE_COMPARATOR); for (Language language : languages) { @SuppressWarnings("UseOfObsoleteCollectionType") - final Hashtable<Integer, JLabel> sliderLabels = new Hashtable<Integer, JLabel>(); + final Hashtable<Integer, JComponent> sliderLabels = new Hashtable<Integer, JComponent>(); sliderLabels.put(1, new JLabel(EditorBundle.message("hector.none.slider.label"))); sliderLabels.put(2, new JLabel(EditorBundle.message("hector.syntax.slider.label"))); if (notInLibrary) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockEndAction.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockEndAction.java index e7c723c17f8b..28b733cb1d5c 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockEndAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockEndAction.java @@ -26,10 +26,12 @@ package com.intellij.codeInsight.editorActions; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.Nullable; public class CodeBlockEndAction extends EditorAction { public CodeBlockEndAction() { @@ -43,7 +45,7 @@ public class CodeBlockEndAction extends EditorAction { } @Override - public void execute(Editor editor, DataContext dataContext) { + public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) { Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null) { CodeBlockUtil.moveCaretToCodeBlockEnd(project, editor, false); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockEndWithSelectionAction.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockEndWithSelectionAction.java index 9431da1fc4d7..10a71a5edc86 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockEndWithSelectionAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockEndWithSelectionAction.java @@ -26,10 +26,12 @@ package com.intellij.codeInsight.editorActions; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.Nullable; public class CodeBlockEndWithSelectionAction extends EditorAction { public CodeBlockEndWithSelectionAction() { @@ -43,7 +45,7 @@ public class CodeBlockEndWithSelectionAction extends EditorAction { } @Override - public void execute(Editor editor, DataContext dataContext) { + public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) { Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null) { CodeBlockUtil.moveCaretToCodeBlockEnd(project, editor, true); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockStartAction.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockStartAction.java index 690efff63d16..fc8ac9cf119a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockStartAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockStartAction.java @@ -26,10 +26,12 @@ package com.intellij.codeInsight.editorActions; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.Nullable; public class CodeBlockStartAction extends EditorAction { public CodeBlockStartAction() { @@ -43,7 +45,7 @@ public class CodeBlockStartAction extends EditorAction { } @Override - public void execute(Editor editor, DataContext dataContext) { + public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) { Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null) { CodeBlockUtil.moveCaretToCodeBlockStart(project, editor, false); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockStartWithSelectionAction.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockStartWithSelectionAction.java index 9819efcdc439..fcae25ac1a2b 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockStartWithSelectionAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CodeBlockStartWithSelectionAction.java @@ -26,10 +26,12 @@ package com.intellij.codeInsight.editorActions; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.Nullable; public class CodeBlockStartWithSelectionAction extends EditorAction { public CodeBlockStartWithSelectionAction() { @@ -43,7 +45,7 @@ public class CodeBlockStartWithSelectionAction extends EditorAction { } @Override - public void execute(Editor editor, DataContext dataContext) { + public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) { Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null) { CodeBlockUtil.moveCaretToCodeBlockStart(project, editor, true); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/EnterHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/EnterHandler.java index c8a1ab3b7730..5db0a1a7e93b 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/EnterHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/EnterHandler.java @@ -61,8 +61,8 @@ public class EnterHandler extends BaseEnterHandler { } @Override - public boolean isEnabled(Editor editor, DataContext dataContext) { - return myOriginalHandler.isEnabled(editor, dataContext); + public boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) { + return myOriginalHandler.isEnabled(editor, caret, dataContext); } @Override diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java index eebdb50ea2ee..5f416dd307c4 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java @@ -239,7 +239,7 @@ public class JoinLinesHandler extends EditorWriteActionHandler { docManager.commitDocument(doc); try { - CodeStyleManager.getInstance(project).reformatText(psiFile, start + 1, end); + CodeStyleManager.getInstance(project).reformatRange(psiFile, start + 1, end, true); } catch (IncorrectOperationException e) { LOG.error(e); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordHandler.java index 8edbb3f5f11d..bfddf17054b5 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordHandler.java @@ -25,6 +25,7 @@ import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; @@ -51,14 +52,14 @@ public class SelectWordHandler extends EditorActionHandler { } @Override - public void execute(@NotNull Editor editor, DataContext dataContext) { + public void doExecute(@NotNull Editor editor, @Nullable Caret caret, DataContext dataContext) { if (LOG.isDebugEnabled()) { LOG.debug("enter: execute(editor='" + editor + "')"); } Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(editor.getComponent())); if (project == null) { if (myOriginalHandler != null) { - myOriginalHandler.execute(editor, dataContext); + myOriginalHandler.execute(editor, caret, dataContext); } return; } @@ -74,7 +75,7 @@ public class SelectWordHandler extends EditorActionHandler { } if (range == null) { if (myOriginalHandler != null) { - myOriginalHandler.execute(editor, dataContext); + myOriginalHandler.execute(editor, caret, dataContext); } } else { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/UnSelectWordHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/UnSelectWordHandler.java index cb1d0a6f2be9..de59e9e8fa6b 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/UnSelectWordHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/UnSelectWordHandler.java @@ -19,6 +19,7 @@ package com.intellij.codeInsight.editorActions; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.FoldRegion; @@ -28,6 +29,7 @@ import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.util.Processor; +import org.jetbrains.annotations.Nullable; public class UnSelectWordHandler extends EditorActionHandler { private final EditorActionHandler myOriginalHandler; @@ -38,14 +40,17 @@ public class UnSelectWordHandler extends EditorActionHandler { } @Override - public void execute(Editor editor, DataContext dataContext) { + public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) { Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(editor.getComponent())); + if (project == null) { + return; + } Document document = editor.getDocument(); final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); if (file == null) { if (myOriginalHandler != null) { - myOriginalHandler.execute(editor, dataContext); + myOriginalHandler.execute(editor, caret, dataContext); } return; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/smartEnter/SmartEnterAction.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/smartEnter/SmartEnterAction.java index bbb1e163729e..19fb28086099 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/smartEnter/SmartEnterAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/smartEnter/SmartEnterAction.java @@ -16,13 +16,13 @@ package com.intellij.codeInsight.editorActions.smartEnter; -import com.intellij.codeInsight.actions.BaseCodeInsightAction; import com.intellij.codeInsight.editorActions.enter.EnterAfterUnmatchedBraceHandler; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.lang.Language; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.IdeActions; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; @@ -41,15 +41,7 @@ import java.util.List; public class SmartEnterAction extends EditorAction { public SmartEnterAction() { super(new Handler()); - } - - @Override - protected Editor getEditor(@NotNull final DataContext dataContext) { - final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); - if (editor == null) return null; - Project project = editor.getProject(); - if (project == null) project = CommonDataKeys.PROJECT.getData(dataContext); - return project == null ? null : BaseCodeInsightAction.getInjectedEditor(project, editor); + setInjectedContext(true); } private static class Handler extends EditorWriteActionHandler { @@ -58,15 +50,15 @@ public class SmartEnterAction extends EditorAction { } @Override - public boolean isEnabled(Editor editor, DataContext dataContext) { - return getEnterHandler().isEnabled(editor, dataContext); + public boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) { + return getEnterHandler().isEnabled(editor, caret, dataContext); } @Override - public void executeWriteAction(Editor editor, DataContext dataContext) { + public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) { Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null || editor.isOneLineMode()) { - plainEnter(editor, dataContext); + plainEnter(editor, caret, dataContext); return; } @@ -76,13 +68,13 @@ public class SmartEnterAction extends EditorAction { PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project); if (psiFile == null) { - plainEnter(editor, dataContext); + plainEnter(editor, caret, dataContext); return; } if (EnterAfterUnmatchedBraceHandler.isAfterUnmatchedLBrace(editor, caretOffset, psiFile.getFileType())) { EditorActionHandler enterHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER); - enterHandler.execute(editor, dataContext); + enterHandler.execute(editor, caret, dataContext); return; } @@ -100,13 +92,13 @@ public class SmartEnterAction extends EditorAction { } } if (!processed) { - plainEnter(editor, dataContext); + plainEnter(editor, caret, dataContext); } } } - public static void plainEnter(Editor editor, DataContext dataContext) { - getEnterHandler().execute(editor, dataContext); + public static void plainEnter(Editor editor, Caret caret, DataContext dataContext) { + getEnterHandler().execute(editor, caret, dataContext); } private static EditorActionHandler getEnterHandler() { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/FoldingUpdate.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/FoldingUpdate.java index 7d0b4453c517..4c137f8d2a37 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/FoldingUpdate.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/FoldingUpdate.java @@ -174,7 +174,7 @@ public class FoldingUpdate { injectedFiles.add(injectedFile); final FoldingMap map = new FoldingMap(); maps.add(map); - getFoldingsFor(injectedFile, injectedDocument, map, false); + getFoldingsFor(injectedFile, injectedEditor.getDocument(), map, false); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/PsiNamesElementSignatureProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/PsiNamesElementSignatureProvider.java index 17a85304d4a1..3409d3f93fc8 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/PsiNamesElementSignatureProvider.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/PsiNamesElementSignatureProvider.java @@ -89,11 +89,23 @@ public class PsiNamesElementSignatureProvider extends AbstractElementSignaturePr return candidate instanceof PsiComment ? candidate : null; } else if (CODE_BLOCK_MARKER.equals(elementMarker)) { + int index = 0; + if (tokenizer.hasMoreTokens()) { + String indexStr = tokenizer.nextToken(); + try { + index = Integer.parseInt(indexStr); + } + catch (NumberFormatException e) { + if (processingInfoStorage != null) { + processingInfoStorage.append("Invalid block index: ").append(indexStr).append("\n"); + } + } + } for (PsiElement child = parent.getFirstChild(); child != null; child = child.getNextSibling()) { - PsiElement firstChild = child.getFirstChild(); - PsiElement lastChild = child.getLastChild(); - if (firstChild != null && lastChild != null && "{".equals(firstChild.getText()) && "}".equals(lastChild.getText())) { - return child; + if (isBlockElement(child)) { + if (--index < 0) { + return child; + } } } return null; @@ -212,18 +224,39 @@ public class PsiNamesElementSignatureProvider extends AbstractElementSignaturePr PsiElement parent = element.getParent(); if (parent instanceof PsiNamedElement && !(parent instanceof PsiFile)) { - PsiElement firstChild = element.getFirstChild(); - PsiElement lastChild = element.getLastChild(); - if (firstChild != null && "{".equals(firstChild.getText()) && lastChild != null && "}".equals(lastChild.getText())) { + if (isBlockElement(element)) { + int index = getBlockElementIndex(element); StringBuilder bufferToUse = buffer; if (bufferToUse == null) { bufferToUse = new StringBuilder(); } bufferToUse.append(TYPE_MARKER).append(ELEMENT_TOKENS_SEPARATOR).append(CODE_BLOCK_MARKER); + if (index > 0) { + bufferToUse.append(ELEMENT_TOKENS_SEPARATOR).append(index); + } return bufferToUse; } } return null; } + + private static boolean isBlockElement(@NotNull PsiElement element) { + PsiElement firstChild = element.getFirstChild(); + PsiElement lastChild = element.getLastChild(); + return firstChild != null && "{".equals(firstChild.getText()) && lastChild != null && "}".equals(lastChild.getText()); + } + + private static int getBlockElementIndex(@NotNull PsiElement element) { + int i = 0; + for (PsiElement sibling : element.getParent().getChildren()) { + if (element.equals(sibling)) { + return i; + } + if (isBlockElement(sibling)) { + i++; + } + } + throw new RuntimeException("Malformed PSI"); + } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditAction.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditAction.java index ee4c91972046..62e3bcba3a22 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditAction.java @@ -25,7 +25,10 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.Balloon; -import com.intellij.openapi.util.*; +import com.intellij.openapi.util.Condition; +import com.intellij.openapi.util.Key; +import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; @@ -138,7 +141,7 @@ public class QuickEditAction implements IntentionAction, LowPriorityAction { } @Nullable - protected JComponent createBalloonComponent(PsiFile file, Ref<Balloon> ref) { + protected JComponent createBalloonComponent(@NotNull PsiFile file) { return null; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditHandler.java index 2f4aa4198f85..2c5d8642e46d 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/QuickEditHandler.java @@ -55,6 +55,7 @@ import com.intellij.psi.impl.source.PostprocessReformattingAspect; import com.intellij.psi.impl.source.resolve.FileContextUtil; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.impl.source.tree.injected.Place; +import com.intellij.psi.util.PsiUtilCore; import com.intellij.testFramework.LightVirtualFile; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.DocumentUtil; @@ -108,18 +109,19 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { myEditor = editor; myAction = action; myOrigDocument = editor.getDocument(); - final Place shreds = InjectedLanguageUtil.getShreds(injectedFile); - final FileType fileType = injectedFile.getFileType(); - final Language language = injectedFile.getLanguage(); - - final PsiFileFactory factory = PsiFileFactory.getInstance(project); - final String text = InjectedLanguageManager.getInstance(project).getUnescapedText(injectedFile); - final String newFileName = + Place shreds = InjectedLanguageUtil.getShreds(injectedFile); + FileType fileType = injectedFile.getFileType(); + Language language = injectedFile.getLanguage(); + PsiLanguageInjectionHost.Shred firstShred = ContainerUtil.getFirstItem(shreds); + + PsiFileFactory factory = PsiFileFactory.getInstance(project); + String text = InjectedLanguageManager.getInstance(project).getUnescapedText(injectedFile); + String newFileName = StringUtil.notNullize(language.getDisplayName(), "Injected") + " Fragment " + "(" + - origFile.getName() + ":" + shreds.get(0).getHost().getTextRange().getStartOffset() + ")" + "." + fileType.getDefaultExtension(); + origFile.getName() + ":" + firstShred.getHost().getTextRange().getStartOffset() + ")" + "." + fileType.getDefaultExtension(); // preserve \r\n as it is done in MultiHostRegistrarImpl - myNewFile = factory.createFileFromText(newFileName, language, text, true, true); + myNewFile = factory.createFileFromText(newFileName, language, text, true, false); myNewVirtualFile = ObjectUtils.assertNotNull((LightVirtualFile)myNewFile.getVirtualFile()); myNewVirtualFile.setOriginalFile(origFile.getVirtualFile()); @@ -130,8 +132,7 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { // suppress possible errors as in injected mode myNewFile.putUserData(InjectedLanguageUtil.FRANKENSTEIN_INJECTION, injectedFile.getUserData(InjectedLanguageUtil.FRANKENSTEIN_INJECTION)); - final SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(project); - myNewFile.putUserData(FileContextUtil.INJECTED_IN_ELEMENT, smartPointerManager.createSmartPsiElementPointer(origFile)); + myNewFile.putUserData(FileContextUtil.INJECTED_IN_ELEMENT, shreds.getHostPointer()); myNewDocument = PsiDocumentManager.getInstance(project).getDocument(myNewFile); assert myNewDocument != null; EditorActionManager.getInstance().setReadonlyFragmentModificationHandler(myNewDocument, new MyQuietHandler()); @@ -149,22 +150,23 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { if (event.getEditor().getDocument() != myNewDocument) return; myEditorCount ++; final EditorActionHandler editorEscape = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ESCAPE); - new AnAction() { - @Override - public void update(AnActionEvent e) { - Editor editor = CommonDataKeys.EDITOR.getData(e.getDataContext()); - e.getPresentation().setEnabled( - !myAction.isShowInBalloon() && - editor != null && LookupManager.getActiveLookup(editor) == null && - TemplateManager.getInstance(myProject).getActiveTemplate(editor) == null && - (editorEscape == null || !editorEscape.isEnabled(editor, e.getDataContext()))); - } + if (!myAction.isShowInBalloon()) { + new AnAction() { + @Override + public void update(AnActionEvent e) { + Editor editor = CommonDataKeys.EDITOR.getData(e.getDataContext()); + e.getPresentation().setEnabled( + editor != null && LookupManager.getActiveLookup(editor) == null && + TemplateManager.getInstance(myProject).getActiveTemplate(editor) == null && + (editorEscape == null || !editorEscape.isEnabled(editor, e.getDataContext()))); + } - @Override - public void actionPerformed(AnActionEvent e) { - closeEditor(); - } - }.registerCustomShortcutSet(CommonShortcuts.ESCAPE, event.getEditor().getContentComponent()); + @Override + public void actionPerformed(AnActionEvent e) { + closeEditor(); + } + }.registerCustomShortcutSet(CommonShortcuts.ESCAPE, event.getEditor().getContentComponent()); + } } @Override @@ -178,10 +180,11 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { } }, this); - if ("JAVA".equals(shreds.get(0).getHost().getLanguage().getID())) { + if ("JAVA".equals(firstShred.getHost().getLanguage().getID())) { + PsiLanguageInjectionHost.Shred lastShred = ContainerUtil.getLastItem(shreds); myAltFullRange = myOrigDocument.createRangeMarker( - shreds.get(0).getHostRangeMarker().getStartOffset(), - shreds.get(shreds.size() - 1).getHostRangeMarker().getEndOffset()); + firstShred.getHostRangeMarker().getStartOffset(), + lastShred.getHostRangeMarker().getEndOffset()); myAltFullRange.setGreedyToLeft(true); myAltFullRange.setGreedyToRight(true); @@ -201,8 +204,7 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { public void navigate(int injectedOffset) { if (myAction.isShowInBalloon()) { - Ref<Balloon> ref = Ref.create(null); - final JComponent component = myAction.createBalloonComponent(myNewFile, ref); + final JComponent component = myAction.createBalloonComponent(myNewFile); if (component != null) { final Balloon balloon = JBPopupFactory.getInstance().createBalloonBuilder(component) .setShadow(true) @@ -212,7 +214,12 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { .setHideOnAction(false) .setFillColor(UIUtil.getControlColor()) .createBalloon(); - ref.set(balloon); + new AnAction() { + @Override + public void actionPerformed(AnActionEvent e) { + balloon.hide(); + } + }.registerCustomShortcutSet(CommonShortcuts.ESCAPE, component); Disposer.register(myNewFile.getProject(), balloon); final Balloon.Position position = QuickEditAction.getBalloonPosition(myEditor); RelativePoint point = JBPopupFactory.getInstance().guessBestPopupLocation(myEditor); @@ -353,11 +360,10 @@ public class QuickEditHandler extends DocumentAdapter implements Disposable { private void commitToOriginal() { if (!isValid()) return; - final PsiFile origFile = (PsiFile)myNewFile.getUserData(FileContextUtil.INJECTED_IN_ELEMENT).getElement(); - VirtualFile origFileVirtualFile = origFile != null? origFile.getVirtualFile() : null; + VirtualFile origVirtualFile = PsiUtilCore.getVirtualFile(ObjectUtils.assertNotNull(myNewFile.getContext())); myCommittingToOriginal = true; try { - if (origFileVirtualFile == null || !ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(origFileVirtualFile).hasReadonlyFiles()) { + if (origVirtualFile == null || !ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(origVirtualFile).hasReadonlyFiles()) { PostprocessReformattingAspect.getInstance(myProject).disablePostprocessFormattingInside(new Runnable() { @Override public void run() { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java index 3666b4642efd..2f56d3714943 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java @@ -19,6 +19,7 @@ package com.intellij.codeInsight.navigation; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.TargetElementUtilBase; import com.intellij.codeInsight.documentation.DocumentationManager; +import com.intellij.codeInsight.documentation.DocumentationManagerProtocol; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.codeInsight.hint.HintUtil; @@ -34,9 +35,7 @@ import com.intellij.openapi.actionSystem.MouseShortcut; import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.actionSystem.impl.ActionButton; import com.intellij.openapi.actionSystem.impl.PresentationFactory; -import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.components.AbstractProjectComponent; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; @@ -66,7 +65,7 @@ import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Comparing; -import com.intellij.openapi.util.Key; +import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; @@ -104,16 +103,14 @@ import java.util.List; public class CtrlMouseHandler extends AbstractProjectComponent { private static final AbstractDocumentationTooltipAction[] ourTooltipActions = {new ShowQuickDocAtPinnedWindowFromTooltipAction()}; - private static Key<?> ourDebuggerHighlighterKey; - private static Key<?> ourXDebuggerHighlighterKey; private final EditorColorsManager myEditorColorsManager; - private HighlightersSet myHighlighter; - @JdkConstants.InputEventMask private int myStoredModifiers = 0; - private TooltipProvider myTooltipProvider = null; - private final FileEditorManager myFileEditorManager; - private final DocumentationManager myDocumentationManager; - @Nullable private Point myPrevMouseLocation; + private HighlightersSet myHighlighter; + @JdkConstants.InputEventMask private int myStoredModifiers = 0; + private TooltipProvider myTooltipProvider = null; + private final FileEditorManager myFileEditorManager; + private final DocumentationManager myDocumentationManager; + @Nullable private Point myPrevMouseLocation; private LightweightHint myHint; private enum BrowseMode {None, Declaration, TypeDeclaration, Implementation} @@ -137,7 +134,11 @@ public class CtrlMouseHandler extends AbstractProjectComponent { BrowseMode browseMode = getBrowseMode(modifiers); - if (browseMode != BrowseMode.None) { + if (browseMode == BrowseMode.None) { + disposeHighlighter(); + cancelPreviousTooltip(); + } + else { TooltipProvider tooltipProvider = myTooltipProvider; if (tooltipProvider != null) { if (browseMode != tooltipProvider.getBrowseMode()) { @@ -149,10 +150,6 @@ public class CtrlMouseHandler extends AbstractProjectComponent { myTooltipProvider.execute(browseMode); } } - else { - disposeHighlighter(); - cancelPreviousTooltip(); - } } }; @@ -240,8 +237,7 @@ public class CtrlMouseHandler extends AbstractProjectComponent { EditorColorsManager colorsManager, FileEditorManager fileEditorManager, @NotNull DocumentationManager documentationManager, - @NotNull final EditorFactory editorFactory) - { + @NotNull final EditorFactory editorFactory) { super(project); myEditorColorsManager = colorsManager; startupManager.registerPostStartupActivity(new DumbAwareRunnable() { @@ -289,6 +285,7 @@ public class CtrlMouseHandler extends AbstractProjectComponent { return new Rectangle(hintComponent.getLocationOnScreen(), hintComponent.getSize()); } + @NotNull private static BrowseMode getBrowseMode(@JdkConstants.InputEventMask int modifiers) { if (modifiers != 0) { final Keymap activeKeymap = KeymapManager.getInstance().getActiveKeymap(); @@ -375,9 +372,9 @@ public class CtrlMouseHandler extends AbstractProjectComponent { private abstract static class Info { @NotNull protected final PsiElement myElementAtPointer; - private final List<TextRange> myRanges; + @NotNull private final List<TextRange> myRanges; - public Info(@NotNull PsiElement elementAtPointer, List<TextRange> ranges) { + public Info(@NotNull PsiElement elementAtPointer, @NotNull List<TextRange> ranges) { myElementAtPointer = elementAtPointer; myRanges = ranges; } @@ -387,10 +384,11 @@ public class CtrlMouseHandler extends AbstractProjectComponent { elementAtPointer.getTextOffset() + elementAtPointer.getTextLength()))); } - boolean isSimilarTo(final Info that) { + boolean isSimilarTo(@NotNull Info that) { return Comparing.equal(myElementAtPointer, that.myElementAtPointer) && myRanges.equals(that.myRanges); } + @NotNull public List<TextRange> getRanges() { return myRanges; } @@ -398,11 +396,11 @@ public class CtrlMouseHandler extends AbstractProjectComponent { @NotNull public abstract DocInfo getInfo(); - public abstract boolean isValid(Document document); + public abstract boolean isValid(@NotNull Document document); public abstract void showDocInfo(@NotNull DocumentationManager docManager); - protected boolean rangesAreCorrect(Document document) { + protected boolean rangesAreCorrect(@NotNull Document document) { final TextRange docRange = new TextRange(0, document.getTextLength()); for (TextRange range : getRanges()) { if (!docRange.contains(range)) return false; @@ -412,7 +410,7 @@ public class CtrlMouseHandler extends AbstractProjectComponent { } } - private static void showDumbModeNotification(final Project project) { + private static void showDumbModeNotification(@NotNull Project project) { DumbService.getInstance(project).showDumbModeNotification("Element information is not available during index update"); } @@ -424,7 +422,7 @@ public class CtrlMouseHandler extends AbstractProjectComponent { myTargetElement = targetElement; } - public InfoSingle(final PsiReference ref, @NotNull final PsiElement targetElement) { + public InfoSingle(@NotNull PsiReference ref, @NotNull final PsiElement targetElement) { super(ref.getElement(), ReferenceRange.getAbsoluteRanges(ref)); myTargetElement = targetElement; } @@ -432,21 +430,22 @@ public class CtrlMouseHandler extends AbstractProjectComponent { @Override @NotNull public DocInfo getInfo() { - AccessToken token = ReadAction.start(); - try { - return generateInfo(myTargetElement, myElementAtPointer); - } - catch (IndexNotReadyException e) { - showDumbModeNotification(myTargetElement.getProject()); - return DocInfo.EMPTY; - } - finally { - token.finish(); - } + return ApplicationManager.getApplication().runReadAction(new Computable<DocInfo>() { + @Override + public DocInfo compute() { + try { + return generateInfo(myTargetElement, myElementAtPointer); + } + catch (IndexNotReadyException e) { + showDumbModeNotification(myTargetElement.getProject()); + return DocInfo.EMPTY; + } + } + }); } @Override - public boolean isValid(Document document) { + public boolean isValid(@NotNull Document document) { if (!myTargetElement.isValid()) return false; if (!myElementAtPointer.isValid()) return false; if (myTargetElement == myElementAtPointer) return false; @@ -462,7 +461,6 @@ public class CtrlMouseHandler extends AbstractProjectComponent { } private static class InfoMultiple extends Info { - public InfoMultiple(@NotNull final PsiElement elementAtPointer) { super(elementAtPointer); } @@ -478,7 +476,7 @@ public class CtrlMouseHandler extends AbstractProjectComponent { } @Override - public boolean isValid(Document document) { + public boolean isValid(@NotNull Document document) { return rangesAreCorrect(document); } @@ -489,7 +487,7 @@ public class CtrlMouseHandler extends AbstractProjectComponent { } @Nullable - private Info getInfoAt(@NotNull Editor editor, PsiFile file, int offset, BrowseMode browseMode) { + private Info getInfoAt(@NotNull Editor editor, @NotNull PsiFile file, int offset, @NotNull BrowseMode browseMode) { PsiElement targetElement = null; if (browseMode == BrowseMode.TypeDeclaration) { @@ -502,7 +500,7 @@ public class CtrlMouseHandler extends AbstractProjectComponent { } else if (browseMode == BrowseMode.Declaration) { final PsiReference ref = TargetElementUtilBase.findReference(editor, offset); - final List<PsiElement> resolvedElements = ref != null ? resolve(ref) : Collections.<PsiElement>emptyList(); + final List<PsiElement> resolvedElements = ref == null ? Collections.<PsiElement>emptyList() : resolve(ref); final PsiElement resolvedElement = resolvedElements.size() == 1 ? resolvedElements.get(0) : null; final PsiElement[] targetElements = GotoDeclarationAction.findTargetElementsNoVS(myProject, editor, offset, false); @@ -572,7 +570,8 @@ public class CtrlMouseHandler extends AbstractProjectComponent { return null; } - private static List<PsiElement> resolve(final PsiReference ref) { + @NotNull + private static List<PsiElement> resolve(@NotNull PsiReference ref) { // IDEA-56727 try resolve first as in GotoDeclarationAction PsiElement resolvedElement = ref.resolve(); @@ -734,13 +733,13 @@ public class CtrlMouseHandler extends AbstractProjectComponent { } private class TooltipProvider { - private final Editor myEditor; - private final LogicalPosition myPosition; + @NotNull private final Editor myEditor; + @NotNull private final LogicalPosition myPosition; private BrowseMode myBrowseMode; private boolean myDisposed; private final ProgressIndicator myProgress = new ProgressIndicatorBase(); - TooltipProvider(Editor editor, LogicalPosition pos) { + TooltipProvider(@NotNull Editor editor, @NotNull LogicalPosition pos) { myEditor = editor; myPosition = pos; } @@ -754,7 +753,7 @@ public class CtrlMouseHandler extends AbstractProjectComponent { return myBrowseMode; } - void execute(BrowseMode browseMode) { + void execute(@NotNull BrowseMode browseMode) { myBrowseMode = browseMode; Document document = myEditor.getDocument(); @@ -785,16 +784,16 @@ public class CtrlMouseHandler extends AbstractProjectComponent { }); } - private void doExecute(PsiFile file, int offset) { + private void doExecute(@NotNull PsiFile file, int offset) { final Info info; try { info = getInfoAt(myEditor, file, offset, myBrowseMode); + if (info == null) return; } catch (IndexNotReadyException e) { showDumbModeNotification(myProject); return; } - if (info == null) return; ApplicationManager.getApplication().invokeLater(new Runnable() { @Override @@ -805,7 +804,7 @@ public class CtrlMouseHandler extends AbstractProjectComponent { }); } - private void showHint(Info info) { + private void showHint(@NotNull Info info) { if (myDisposed || myEditor.isDisposed()) return; Component internalComponent = myEditor.getContentComponent(); if (myHighlighter != null) { @@ -856,10 +855,6 @@ public class CtrlMouseHandler extends AbstractProjectComponent { @Override public void mouseClicked(MouseEvent e) { - QuickDocInfoPane pane = quickDocPaneRef.get(); - if (pane != null) { - pane.mouseClicked(e); - } } }; Ref<Consumer<String>> newTextConsumerRef = new Ref<Consumer<String>>(); @@ -889,7 +884,7 @@ public class CtrlMouseHandler extends AbstractProjectComponent { showHint(hint); } - public void showHint(LightweightHint hint) { + public void showHint(@NotNull LightweightHint hint) { final HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); Point p = HintManagerImpl.getHintPosition(hint, myEditor, myPosition, HintManager.ABOVE); hintManager.showEditorHint(hint, myEditor, p, @@ -898,7 +893,8 @@ public class CtrlMouseHandler extends AbstractProjectComponent { } } - private HighlightersSet installHighlighterSet(Info info, Editor editor) { + @NotNull + private HighlightersSet installHighlighterSet(@NotNull Info info, @NotNull Editor editor) { final JComponent internalComponent = editor.getContentComponent(); internalComponent.addKeyListener(myEditorKeyListener); editor.getScrollingModel().addVisibleAreaListener(myVisibleAreaListener); @@ -922,12 +918,15 @@ public class CtrlMouseHandler extends AbstractProjectComponent { private class HighlightersSet { - private final List<RangeHighlighter> myHighlighters; - private final Editor myHighlighterView; - private final Cursor myStoredCursor; - private final Info myStoredInfo; - - private HighlightersSet(List<RangeHighlighter> highlighters, Editor highlighterView, Cursor storedCursor, Info storedInfo) { + @NotNull private final List<RangeHighlighter> myHighlighters; + @NotNull private final Editor myHighlighterView; + @NotNull private final Cursor myStoredCursor; + @NotNull private final Info myStoredInfo; + + private HighlightersSet(@NotNull List<RangeHighlighter> highlighters, + @NotNull Editor highlighterView, + @NotNull Cursor storedCursor, + @NotNull Info storedInfo) { myHighlighters = highlighters; myHighlighterView = highlighterView; myStoredCursor = storedCursor; @@ -946,18 +945,18 @@ public class CtrlMouseHandler extends AbstractProjectComponent { myFileEditorManager.removeFileEditorManagerListener(myFileEditorManagerListener); } + @NotNull public Info getStoredInfo() { return myStoredInfo; } } private static class DocInfo { - public static final DocInfo EMPTY = new DocInfo(null, null, null); - @Nullable public final String text; + @Nullable public final String text; @Nullable public final DocumentationProvider docProvider; - @Nullable public final PsiElement documentationAnchor; + @Nullable public final PsiElement documentationAnchor; DocInfo(@Nullable String text, @Nullable DocumentationProvider provider, @Nullable PsiElement documentationAnchor) { this.text = text; @@ -967,7 +966,6 @@ public class CtrlMouseHandler extends AbstractProjectComponent { } private class QuickDocInfoPane extends JBLayeredPane { - private static final int BUTTON_HGAP = 5; @NotNull private final List<JComponent> myButtons = new ArrayList<JComponent>(); @@ -1073,11 +1071,6 @@ public class CtrlMouseHandler extends AbstractProjectComponent { processStateChangeIfNecessary(e.getLocationOnScreen(), false); } - public void mouseClicked(@NotNull MouseEvent e) { - // TODO den check the processing. - int i = 1; - } - private void processStateChangeIfNecessary(@NotNull Point mouseScreenLocation, boolean mouseEntered) { // Don't show 'view quick doc' buttons if docked quick doc control is already active. if (myDocumentationManager.hasActiveDockedDocWindow()) { @@ -1095,9 +1088,8 @@ public class CtrlMouseHandler extends AbstractProjectComponent { } private class QuickDocHyperlinkListener implements HyperlinkListener { - @NotNull private final DocumentationProvider myProvider; - @NotNull private final PsiElement myContext; + @NotNull private final PsiElement myContext; QuickDocHyperlinkListener(@NotNull DocumentationProvider provider, @NotNull PsiElement context) { myProvider = provider; @@ -1111,11 +1103,11 @@ public class CtrlMouseHandler extends AbstractProjectComponent { } String description = e.getDescription(); - if (StringUtil.isEmpty(description) || !description.startsWith(DocumentationManager.PSI_ELEMENT_PROTOCOL)) { + if (StringUtil.isEmpty(description) || !description.startsWith(DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL)) { return; } - String elementName = e.getDescription().substring(DocumentationManager.PSI_ELEMENT_PROTOCOL.length()); + String elementName = e.getDescription().substring(DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL.length()); final PsiElement targetElement = myProvider.getDocumentationElementForLink(PsiManager.getInstance(myProject), elementName, myContext); if (targetElement != null) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/actions/NextVariableAction.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/actions/NextVariableAction.java index 6605dacbc209..102626785a24 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/actions/NextVariableAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/actions/NextVariableAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,11 +28,13 @@ import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.command.CommandProcessor; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class NextVariableAction extends EditorAction { public NextVariableAction() { @@ -42,16 +44,17 @@ public class NextVariableAction extends EditorAction { private static class Handler extends EditorWriteActionHandler { @Override - public void executeWriteAction(Editor editor, DataContext dataContext) { + public void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext) { TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); + assert templateState != null; CommandProcessor.getInstance().setCurrentCommandName(CodeInsightBundle.message("template.next.variable.command")); templateState.nextTab(); } - } - @Override - public void update(Editor editor, Presentation presentation, DataContext dataContext) { - TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); - presentation.setEnabled(templateState != null && !templateState.isFinished() && templateState.isToProcessTab()); + @Override + protected boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) { + TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); + return templateState != null && !templateState.isFinished() && templateState.isToProcessTab(); + } } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/actions/PreviousVariableAction.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/actions/PreviousVariableAction.java index bbb1f6a2bdf7..04a19bdd9b65 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/actions/PreviousVariableAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/actions/PreviousVariableAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,11 +28,12 @@ import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.command.CommandProcessor; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler; +import org.jetbrains.annotations.NotNull; public class PreviousVariableAction extends EditorAction { public PreviousVariableAction() { @@ -42,16 +43,17 @@ public class PreviousVariableAction extends EditorAction { private static class Handler extends EditorWriteActionHandler { @Override - public void executeWriteAction(Editor editor, DataContext dataContext) { + public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) { final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); + assert templateState != null; CommandProcessor.getInstance().setCurrentCommandName(CodeInsightBundle.message("template.previous.variable.command")); templateState.previousTab(); } - } - @Override - public void update(Editor editor, Presentation presentation, DataContext dataContext) { - final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); - presentation.setEnabled(templateState != null && !templateState.isFinished()); + @Override + protected boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) { + final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); + return templateState != null && !templateState.isFinished(); + } } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/editorActions/EnterHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/editorActions/EnterHandler.java index d071b24416b3..de503d125f30 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/editorActions/EnterHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/editorActions/EnterHandler.java @@ -26,6 +26,7 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; +import org.jetbrains.annotations.NotNull; public class EnterHandler extends BaseEnterHandler { private final EditorActionHandler myOriginalHandler; @@ -36,8 +37,8 @@ public class EnterHandler extends BaseEnterHandler { } @Override - public boolean isEnabled(Editor editor, DataContext dataContext) { - return myOriginalHandler.isEnabled(editor, dataContext); + public boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) { + return myOriginalHandler.isEnabled(editor, caret, dataContext); } @Override diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/editorActions/ExpandLiveTemplateByTabAction.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/editorActions/ExpandLiveTemplateByTabAction.java index 13798639227f..326daba46e1e 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/editorActions/ExpandLiveTemplateByTabAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/editorActions/ExpandLiveTemplateByTabAction.java @@ -19,11 +19,13 @@ import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateSettings; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorAction; import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; +import org.jetbrains.annotations.Nullable; /** * @author peter @@ -32,7 +34,7 @@ public class ExpandLiveTemplateByTabAction extends EditorAction { public ExpandLiveTemplateByTabAction() { super(new EditorWriteActionHandler(true) { @Override - public void executeWriteAction(Editor editor, DataContext dataContext) { + public void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext) { Project project = editor.getProject(); assert project != null; PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesCheckboxTree.java b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesCheckboxTree.java index b6a507ec67a2..68d5e7417d2a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesCheckboxTree.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesCheckboxTree.java @@ -17,6 +17,7 @@ package com.intellij.codeInsight.template.postfix.settings; import com.intellij.codeInsight.template.postfix.templates.PostfixTemplate; import com.intellij.ide.util.treeView.TreeState; +import com.intellij.lang.Language; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.CheckboxTree; import com.intellij.ui.CheckedTreeNode; @@ -35,7 +36,10 @@ import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; -import java.util.*; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Map; +import java.util.Set; public class PostfixTemplatesCheckboxTree extends CheckboxTree { @@ -102,7 +106,7 @@ public class PostfixTemplatesCheckboxTree extends CheckboxTree { getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { @Override - public void valueChanged(TreeSelectionEvent event) { + public void valueChanged(@NotNull TreeSelectionEvent event) { selectionChanged(); } }); @@ -117,10 +121,13 @@ public class PostfixTemplatesCheckboxTree extends CheckboxTree { public void initTree(@NotNull MultiMap<String, PostfixTemplate> langToTemplates) { myRoot.removeAllChildren(); for (Map.Entry<String, Collection<PostfixTemplate>> entry : langToTemplates.entrySet()) { - CheckedTreeNode langNode = new CheckedTreeNode(entry.getKey()); + String id = entry.getKey(); + Language language = Language.findLanguageByID(id); + String langName = language != null ? language.getDisplayName() : id; + CheckedTreeNode langNode = new CheckedTreeNode(langName); myRoot.add(langNode); for (PostfixTemplate template : entry.getValue()) { - CheckedTreeNode templateNode = new PostfixTemplateCheckedTreeNode(template, entry.getKey()); + CheckedTreeNode templateNode = new PostfixTemplateCheckedTreeNode(template, langName); langNode.add(templateNode); } } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java index f109d0dfe8dd..090d83389b6c 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java @@ -58,6 +58,7 @@ import com.intellij.psi.*; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.content.*; import com.intellij.util.Processor; import com.intellij.util.SequentialModalProgressTask; @@ -354,7 +355,7 @@ public class GlobalInspectionContextImpl extends GlobalInspectionContextBase imp final FileViewProvider viewProvider = psiManager.findViewProvider(virtualFile); final com.intellij.openapi.editor.Document document = viewProvider == null ? null : viewProvider.getDocument(); - if (document == null || virtualFile.getFileType().isBinary()) return; //do not inspect binary files + if (document == null || isBinary(file)) return; //do not inspect binary files final LocalInspectionsPass pass = new LocalInspectionsPass(file, document, 0, file.getTextLength(), LocalInspectionsPass.EMPTY_PRIORITY_RANGE, true, HighlightInfoProcessor.getEmpty()); @@ -656,8 +657,7 @@ public class GlobalInspectionContextImpl extends GlobalInspectionContextBase imp scope.accept(new PsiElementVisitor() { @Override public void visitFile(PsiFile file) { - final VirtualFile virtualFile = file.getVirtualFile(); - if (virtualFile == null || virtualFile.getFileType().isBinary()) return; + if (isBinary(file)) return; for (final Tools tools : profile.getAllEnabledInspectionTools(project)) { if (tools.getTool().getTool() instanceof CleanupLocalInspectionTool) { final InspectionToolWrapper tool = tools.getEnabledTool(file); @@ -724,4 +724,8 @@ public class GlobalInspectionContextImpl extends GlobalInspectionContextBase imp ApplicationManager.getApplication().invokeLater(runnable); } } + + private static boolean isBinary(PsiFile file) { + return file instanceof PsiBinaryFile || file.getFileType().isBinary(); + } } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/SeverityEditorDialog.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/SeverityEditorDialog.java index 527235b5166c..e239678af0ad 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/SeverityEditorDialog.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/SeverityEditorDialog.java @@ -37,6 +37,7 @@ import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.options.ShowSettingsUtil; +import com.intellij.openapi.options.ex.ConfigurableWrapper; import com.intellij.openapi.options.newEditor.OptionsEditor; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.InputValidator; @@ -231,7 +232,8 @@ public class SeverityEditorDialog extends DialogWrapper { final DataContext dataContext = DataManager.getInstance().getDataContext(myPanel); final OptionsEditor optionsEditor = OptionsEditor.KEY.getData(dataContext); if (optionsEditor != null) { - final ColorAndFontOptions colorAndFontOptions = optionsEditor.findConfigurable(ColorAndFontOptions.class); + final ColorAndFontOptions colorAndFontOptions = + (ColorAndFontOptions)((ConfigurableWrapper)optionsEditor.findConfigurableById(ColorAndFontOptions.ID)).getConfigurable(); assert colorAndFontOptions != null; final SearchableConfigurable javaPage = colorAndFontOptions.findSubConfigurable(InspectionColorSettingsPage.class); LOG.assertTrue(javaPage != null); diff --git a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleManagerBase.java b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleManagerBase.java index 026de56c9491..cb034daeaf5a 100644 --- a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleManagerBase.java +++ b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleManagerBase.java @@ -52,7 +52,9 @@ public abstract class LogConsoleManagerBase implements LogConsoleManager, Dispos /** * @deprecated use {@link #LogConsoleManagerBase(com.intellij.openapi.project.Project, com.intellij.psi.search.GlobalSearchScope)} + * to remove in IDEA 15 */ + @SuppressWarnings("UnusedDeclaration") protected LogConsoleManagerBase(@NotNull Project project) { this(project, GlobalSearchScope.allScope(project)); } @@ -66,8 +68,8 @@ public abstract class LogConsoleManagerBase implements LogConsoleManager, Dispos return myProject; } - public void setEnvironment(@NotNull final ExecutionEnvironment env) { - myEnvironment = env; + public void setEnvironment(@NotNull ExecutionEnvironment environment) { + myEnvironment = environment; } protected final ExecutionEnvironment getEnvironment() { diff --git a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogFilesManager.java b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogFilesManager.java index 05abeb4b7790..a581a15ed6b8 100644 --- a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogFilesManager.java +++ b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogFilesManager.java @@ -23,9 +23,11 @@ import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; +import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.Disposer; import com.intellij.util.Alarm; import gnu.trove.THashSet; +import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.io.File; @@ -36,18 +38,17 @@ import java.util.*; * Date: 01-Feb-2006 */ public class LogFilesManager implements Disposable { - public static final Logger LOG = Logger.getInstance("#" + LogFilesManager.class.getName()); + public static final Logger LOG = Logger.getInstance(LogFilesManager.class); private static final int UPDATE_INTERVAL = 500; private final Map<LogFileOptions, Set<String>> myLogFileManagerMap = new LinkedHashMap<LogFileOptions, Set<String>>(); - private final Map<LogFileOptions, RunConfigurationBase> myLogFileToConfiguration = new HashMap<LogFileOptions, RunConfigurationBase>(); private final Runnable myUpdateRequest; private final LogConsoleManager myManager; private final Alarm myUpdateAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, this); private boolean myDisposed; - public LogFilesManager(final Project project, LogConsoleManager manager, Disposable parentDisposable) { + public LogFilesManager(@NotNull final Project project, LogConsoleManager manager, Disposable parentDisposable) { myManager = manager; Disposer.register(parentDisposable, this); @@ -86,12 +87,11 @@ public class LogFilesManager implements Disposable { }; } - public void registerFileMatcher(final RunConfigurationBase runConfiguration) { + public void registerFileMatcher(@NotNull RunConfigurationBase runConfiguration) { final ArrayList<LogFileOptions> logFiles = runConfiguration.getAllLogFiles(); for (LogFileOptions logFile : logFiles) { if (logFile.isEnabled()) { myLogFileManagerMap.put(logFile, logFile.getPaths()); - myLogFileToConfiguration.put(logFile, runConfiguration); } } Alarm updateAlarm = myUpdateAlarm; @@ -108,11 +108,11 @@ public class LogFilesManager implements Disposable { } } - public void initLogConsoles(RunConfigurationBase base, ProcessHandler startedProcess) { - final ArrayList<LogFileOptions> logFiles = base.getAllLogFiles(); + public void initLogConsoles(@NotNull RunConfigurationBase base, ProcessHandler startedProcess) { + List<LogFileOptions> logFiles = base.getAllLogFiles(); for (LogFileOptions logFile : logFiles) { if (logFile.isEnabled()) { - addConfigurationConsoles(logFile, Condition.TRUE, logFile.getPaths()); + addConfigurationConsoles(logFile, Conditions.<String>alwaysTrue(), logFile.getPaths()); } } base.createAdditionalTabComponents(myManager, startedProcess); diff --git a/platform/lang-impl/src/com/intellij/diagnostic/logging/OutputFileUtil.java b/platform/lang-impl/src/com/intellij/diagnostic/logging/OutputFileUtil.java index fc7e6a342406..1f82f25307a3 100644 --- a/platform/lang-impl/src/com/intellij/diagnostic/logging/OutputFileUtil.java +++ b/platform/lang-impl/src/com/intellij/diagnostic/logging/OutputFileUtil.java @@ -34,6 +34,7 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; @@ -51,41 +52,43 @@ public class OutputFileUtil { private OutputFileUtil() { } - public static void attachDumpListener(final RunConfigurationBase base, final ProcessHandler startedProcess, ExecutionConsole console) { - if (base.isSaveOutputToFile()) { - final String outputFilePath = base.getOutputFilePath(); - if (outputFilePath != null) { - final String filePath = FileUtil.toSystemDependentName(outputFilePath); - startedProcess.addProcessListener(new ProcessAdapter() { - private PrintStream myOutput; - @Override - public void onTextAvailable(ProcessEvent event, Key outputType) { - if (base.collectOutputFromProcessHandler() && myOutput != null && outputType != ProcessOutputTypes.SYSTEM) { - myOutput.print(event.getText()); - } + public static void attachDumpListener(@NotNull final RunConfigurationBase configuration, @NotNull final ProcessHandler startedProcess, @Nullable ExecutionConsole console) { + if (!configuration.isSaveOutputToFile()) { + return; + } + + String outputFilePath = configuration.getOutputFilePath(); + if (outputFilePath != null) { + final String filePath = FileUtil.toSystemDependentName(outputFilePath); + startedProcess.addProcessListener(new ProcessAdapter() { + private PrintStream myOutput; + @Override + public void onTextAvailable(ProcessEvent event, Key outputType) { + if (configuration.collectOutputFromProcessHandler() && myOutput != null && outputType != ProcessOutputTypes.SYSTEM) { + myOutput.print(event.getText()); } + } - @Override - public void startNotified(ProcessEvent event) { - try { - myOutput = new PrintStream(new FileOutputStream(new File(filePath))); - } - catch (FileNotFoundException ignored) { - } - startedProcess.notifyTextAvailable(CONSOLE_OUTPUT_FILE_MESSAGE + filePath + "\n", ProcessOutputTypes.SYSTEM); + @Override + public void startNotified(ProcessEvent event) { + try { + myOutput = new PrintStream(new FileOutputStream(new File(filePath))); + } + catch (FileNotFoundException ignored) { } + startedProcess.notifyTextAvailable(CONSOLE_OUTPUT_FILE_MESSAGE + filePath + "\n", ProcessOutputTypes.SYSTEM); + } - @Override - public void processTerminated(ProcessEvent event) { - startedProcess.removeProcessListener(this); - if (myOutput != null) { - myOutput.close(); - } + @Override + public void processTerminated(ProcessEvent event) { + startedProcess.removeProcessListener(this); + if (myOutput != null) { + myOutput.close(); } - }); - if (console instanceof ConsoleView) { - ((ConsoleView)console).addMessageFilter(new ShowOutputFileFilter()); } + }); + if (console instanceof ConsoleView) { + ((ConsoleView)console).addMessageFilter(new ShowOutputFileFilter()); } } } diff --git a/platform/lang-impl/src/com/intellij/execution/ExecutionHelper.java b/platform/lang-impl/src/com/intellij/execution/ExecutionHelper.java index c4b5eaf71daf..cce4fc571abb 100644 --- a/platform/lang-impl/src/com/intellij/execution/ExecutionHelper.java +++ b/platform/lang-impl/src/com/intellij/execution/ExecutionHelper.java @@ -21,6 +21,7 @@ import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.process.ProcessOutput; import com.intellij.execution.ui.RunContentDescriptor; +import com.intellij.execution.ui.RunContentManager; import com.intellij.ide.errorTreeView.NewErrorTreeViewPanel; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; @@ -44,12 +45,8 @@ import com.intellij.ui.ListCellRendererWrapper; import com.intellij.ui.components.JBList; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentFactory; -import com.intellij.ui.content.ContentManager; import com.intellij.ui.content.MessageView; -import com.intellij.util.ArrayUtil; -import com.intellij.util.Consumer; -import com.intellij.util.Function; -import com.intellij.util.NotNullFunction; +import com.intellij.util.*; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.ErrorTreeView; @@ -170,10 +167,8 @@ public class ExecutionHelper { openMessagesView(errorTreeView, myProject, tabDisplayName); } catch (NullPointerException e) { - final StringBuilder builder = new StringBuilder(); - builder.append(stdOutTitle).append("\n").append(stdout != null ? stdout : "<empty>").append("\n"); - builder.append(stderrTitle).append("\n").append(stderr != null ? stderr : "<empty>"); - Messages.showErrorDialog(builder.toString(), "Process Output"); + Messages.showErrorDialog(stdOutTitle + "\n" + (stdout != null ? stdout : "<empty>") + "\n" + stderrTitle + "\n" + + (stderr != null ? stderr : "<empty>"), "Process Output"); return; } @@ -267,13 +262,12 @@ public class ExecutionHelper { }); } - public static Collection<RunContentDescriptor> findRunningConsole(final Project project, - @NotNull final NotNullFunction<RunContentDescriptor, Boolean> descriptorMatcher) { - final ExecutionManager executionManager = ExecutionManager.getInstance(project); - - final RunContentDescriptor selectedContent = executionManager.getContentManager().getSelectedContent(); + public static Collection<RunContentDescriptor> findRunningConsole(@NotNull Project project, + @NotNull NotNullFunction<RunContentDescriptor, Boolean> descriptorMatcher) { + RunContentManager contentManager = ExecutionManager.getInstance(project).getContentManager(); + final RunContentDescriptor selectedContent = contentManager.getSelectedContent(); if (selectedContent != null) { - final ToolWindow toolWindow = ExecutionManager.getInstance(project).getContentManager().getToolWindowByDescriptor(selectedContent); + final ToolWindow toolWindow = contentManager.getToolWindowByDescriptor(selectedContent); if (toolWindow != null && toolWindow.isVisible()) { if (descriptorMatcher.fun(selectedContent)) { return Collections.singletonList(selectedContent); @@ -282,7 +276,7 @@ public class ExecutionHelper { } final ArrayList<RunContentDescriptor> result = ContainerUtil.newArrayList(); - for (RunContentDescriptor runContentDescriptor : executionManager.getContentManager().getAllDescriptors()) { + for (RunContentDescriptor runContentDescriptor : contentManager.getAllDescriptors()) { if (descriptorMatcher.fun(runContentDescriptor)) { result.add(runContentDescriptor); } @@ -290,11 +284,10 @@ public class ExecutionHelper { return result; } - public static List<RunContentDescriptor> collectConsolesByDisplayName(final Project project, + public static List<RunContentDescriptor> collectConsolesByDisplayName(@NotNull Project project, @NotNull NotNullFunction<String, Boolean> titleMatcher) { - List<RunContentDescriptor> result = ContainerUtil.newArrayList(); - final ExecutionManager executionManager = ExecutionManager.getInstance(project); - for (RunContentDescriptor runContentDescriptor : executionManager.getContentManager().getAllDescriptors()) { + List<RunContentDescriptor> result = new SmartList<RunContentDescriptor>(); + for (RunContentDescriptor runContentDescriptor : ExecutionManager.getInstance(project).getContentManager().getAllDescriptors()) { if (titleMatcher.fun(runContentDescriptor.getDisplayName())) { result.add(runContentDescriptor); } @@ -343,21 +336,18 @@ public class ExecutionHelper { } } - private static void descriptorToFront(final Project project, final RunContentDescriptor descriptor) { + private static void descriptorToFront(@NotNull final Project project, @NotNull final RunContentDescriptor descriptor) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { - final ToolWindow toolWindow = ExecutionManager.getInstance(project).getContentManager().getToolWindowByDescriptor(descriptor); - + ToolWindow toolWindow = ExecutionManager.getInstance(project).getContentManager().getToolWindowByDescriptor(descriptor); if (toolWindow != null) { toolWindow.show(null); - - final ContentManager contentManager = toolWindow.getContentManager(); - - contentManager.setSelectedContent(descriptor.getAttachedContent()); + //noinspection ConstantConditions + toolWindow.getContentManager().setSelectedContent(descriptor.getAttachedContent()); } } - }); + }, project.getDisposed()); } public static class ErrorViewPanel extends NewErrorTreeViewPanel { @@ -384,8 +374,6 @@ public class ExecutionHelper { @NotNull final ExecutionMode mode, @NotNull final String presentableCmdline) { final String title = mode.getTitle() != null ? mode.getTitle() : "Please wait..."; - assert title != null; - final Runnable process; if (mode.cancelable()) { process = createCancelableExecutionProcess(processHandler, mode.shouldCancelFun()); @@ -400,7 +388,7 @@ public class ExecutionHelper { }; } else { - process = createTimelimitedExecutionProcess(processHandler, mode.getTimeout(), presentableCmdline); + process = createTimeLimitedExecutionProcess(processHandler, mode.getTimeout(), presentableCmdline); } } if (mode.withModalProgress()) { @@ -447,7 +435,7 @@ public class ExecutionHelper { private final Runnable myCancelListener = new Runnable() { @Override public void run() { - for (; ; ) { + while (true) { if ((myProgressIndicator != null && (myProgressIndicator.isCanceled() || !myProgressIndicator.isRunning())) || (cancelableFun != null && cancelableFun.fun(null).booleanValue()) @@ -493,7 +481,7 @@ public class ExecutionHelper { }; } - private static Runnable createTimelimitedExecutionProcess(final ProcessHandler processHandler, + private static Runnable createTimeLimitedExecutionProcess(final ProcessHandler processHandler, final int timeout, @NotNull final String presentableCmdline) { return new Runnable() { diff --git a/platform/lang-impl/src/com/intellij/execution/ExecutionTargetManagerImpl.java b/platform/lang-impl/src/com/intellij/execution/ExecutionTargetManagerImpl.java index d0170430613e..e4d7b9cff49e 100644 --- a/platform/lang-impl/src/com/intellij/execution/ExecutionTargetManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/ExecutionTargetManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,11 @@ */ package com.intellij.execution; -import com.intellij.execution.impl.RunManagerImpl; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.components.*; +import com.intellij.openapi.components.PersistentStateComponent; +import com.intellij.openapi.components.State; +import com.intellij.openapi.components.Storage; +import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import com.intellij.util.containers.ContainerUtil; @@ -29,25 +31,30 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; - -@State(name = "ExecutionTargetManager", storages = {@Storage(file = StoragePathMacros.WORKSPACE_FILE, scheme = StorageScheme.DEFAULT)}) -public class ExecutionTargetManagerImpl extends ExecutionTargetManager implements ProjectComponent, PersistentStateComponent<Element> { +@State(name = "ExecutionTargetManager", storages = {@Storage(file = StoragePathMacros.WORKSPACE_FILE)}) +public class ExecutionTargetManagerImpl extends ExecutionTargetManager implements PersistentStateComponent<Element> { @NotNull private final Project myProject; @NotNull private final Object myActiveTargetLock = new Object(); @Nullable private ExecutionTarget myActiveTarget; @Nullable private String mySavedActiveTargetId; - public ExecutionTargetManagerImpl(@NotNull Project project) { + public ExecutionTargetManagerImpl(@NotNull Project project, @NotNull RunManager runManager) { myProject = project; - } - @Override - public void projectOpened() { - } + ((RunManagerEx)runManager).addRunManagerListener(new RunManagerAdapter() { + @Override + public void runConfigurationChanged(@NotNull RunnerAndConfigurationSettings settings) { + if (settings == RunManager.getInstance(myProject).getSelectedConfiguration()) { + updateActiveTarget(settings); + } + } - @Override - public void projectClosed() { + @Override + public void runConfigurationSelected() { + updateActiveTarget(); + } + }); } @Override @@ -70,33 +77,6 @@ public class ExecutionTargetManagerImpl extends ExecutionTargetManager implement } } - @Override - public void initComponent() { - RunManagerImpl.getInstanceImpl(myProject).addRunManagerListener(new RunManagerAdapter() { - @Override - public void runConfigurationChanged(@NotNull RunnerAndConfigurationSettings settings) { - if (settings == RunManager.getInstance(myProject).getSelectedConfiguration()) { - updateActiveTarget(settings); - } - } - - @Override - public void runConfigurationSelected() { - updateActiveTarget(); - } - }); - } - - @Override - public void disposeComponent() { - } - - @NotNull - @Override - public String getComponentName() { - return ExecutionTargetManager.class.getName(); - } - @NotNull @Override public ExecutionTarget getActiveTarget() { @@ -128,7 +108,7 @@ public class ExecutionTargetManagerImpl extends ExecutionTargetManager implement private void updateActiveTarget(@Nullable RunnerAndConfigurationSettings settings, @Nullable ExecutionTarget toSelect) { List<ExecutionTarget> suitable = settings == null ? Collections.singletonList(DefaultExecutionTarget.INSTANCE) : getTargetsFor(settings); - ExecutionTarget toNotify = null; + ExecutionTarget toNotify; synchronized (myActiveTargetLock) { if (toSelect == null) toSelect = myActiveTarget; diff --git a/platform/lang-impl/src/com/intellij/execution/ExecutorRegistryImpl.java b/platform/lang-impl/src/com/intellij/execution/ExecutorRegistryImpl.java index bd9f5014fabb..44af49d36cdd 100644 --- a/platform/lang-impl/src/com/intellij/execution/ExecutorRegistryImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/ExecutorRegistryImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.intellij.execution; import com.intellij.execution.actions.RunContextAction; @@ -35,12 +34,8 @@ import org.jetbrains.annotations.Nullable; import java.util.*; -/** - * @author spleaner - */ public class ExecutorRegistryImpl extends ExecutorRegistry { - private static final Logger LOG = Logger.getInstance("#com.intellij.execution.ExecutorRegistryImpl"); - + private static final Logger LOG = Logger.getInstance(ExecutorRegistryImpl.class); @NonNls public static final String RUNNERS_GROUP = "RunnerActions"; @NonNls public static final String RUN_CONTEXT_GROUP = "RunContextGroup"; @@ -84,8 +79,7 @@ public class ExecutorRegistryImpl extends ExecutorRegistry { action = anAction; } - final DefaultActionGroup group = (DefaultActionGroup) myActionManager.getAction(groupId); - group.add(action); + ((DefaultActionGroup)myActionManager.getAction(groupId)).add(action); } synchronized void deinitExecutor(@NotNull final Executor executor) { @@ -135,18 +129,18 @@ public class ExecutorRegistryImpl extends ExecutorRegistry { final MessageBusConnection connect = project.getMessageBus().connect(project); connect.subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionAdapter(){ @Override - public void processStartScheduled(String executorId, ExecutionEnvironment env) { - myInProgress.add(createExecutionId(executorId, env, project)); + public void processStartScheduled(String executorId, ExecutionEnvironment environment) { + myInProgress.add(createExecutionId(executorId, environment)); } @Override - public void processNotStarted(String executorId, @NotNull ExecutionEnvironment env) { - myInProgress.remove(createExecutionId(executorId, env, project)); + public void processNotStarted(String executorId, @NotNull ExecutionEnvironment environment) { + myInProgress.remove(createExecutionId(executorId, environment)); } @Override - public void processStarted(String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler) { - myInProgress.remove(createExecutionId(executorId, env, project)); + public void processStarted(String executorId, @NotNull ExecutionEnvironment environment, @NotNull ProcessHandler handler) { + myInProgress.remove(createExecutionId(executorId, environment)); } }); } @@ -172,26 +166,29 @@ public class ExecutorRegistryImpl extends ExecutorRegistry { } } - private static Trinity<Project, String, String> createExecutionId(String executorId, ExecutionEnvironment env, Project project) { - return new Trinity<Project, String, String>(project, executorId, env.getRunnerId()); + @NotNull + private static Trinity<Project, String, String> createExecutionId(String executorId, @NotNull ExecutionEnvironment environment) { + return Trinity.create(environment.getProject(), executorId, environment.getRunner().getRunnerId()); } @Override public boolean isStarting(Project project, final String executorId, final String runnerId) { - return myInProgress.contains(new Trinity<Project, String, String>(project, executorId, runnerId)); + return myInProgress.contains(Trinity.create(project, executorId, runnerId)); + } + + @Override + public boolean isStarting(@NotNull ExecutionEnvironment environment) { + return isStarting(environment.getProject(), environment.getExecutor().getId(), environment.getRunner().getRunnerId()); } @Override public synchronized void disposeComponent() { - if (myExecutors.size() > 0) { - List<Executor> executors = new ArrayList<Executor>(myExecutors); - for (Executor executor : executors) { + if (!myExecutors.isEmpty()) { + for (Executor executor : new ArrayList<Executor>(myExecutors)) { deinitExecutor(executor); } - - myExecutors = null; } - + myExecutors = null; myActionManager = null; } @@ -206,7 +203,7 @@ public class ExecutorRegistryImpl extends ExecutorRegistry { @Override public void update(final AnActionEvent e) { final Presentation presentation = e.getPresentation(); - final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext()); + final Project project = e.getProject(); if (project == null || !project.isInitialized() || project.isDisposed() || DumbService.getInstance(project).isDumb()) { presentation.setEnabled(false); @@ -222,7 +219,7 @@ public class ExecutorRegistryImpl extends ExecutorRegistry { ExecutionTarget target = ExecutionTargetManager.getActiveTarget(project); enabled = ExecutionTargetManager.canRun(selectedConfiguration, target) - && runner != null && !isStarting(project, myExecutor.getId(), runner.getRunnerId()); + && runner != null && !isStarting(project, myExecutor.getId(), runner.getRunnerId()); if (enabled) { presentation.setDescription(myExecutor.getDescription()); @@ -244,25 +241,17 @@ public class ExecutorRegistryImpl extends ExecutorRegistry { @Override public void actionPerformed(final AnActionEvent e) { - final DataContext dataContext = e.getDataContext(); final Project project = e.getProject(); if (project == null || project.isDisposed()) { return; } - final RunnerAndConfigurationSettings configuration = getConfiguration(project); - if (configuration == null) { - return; - } - ExecutionTarget target = ExecutionTargetManager.getActiveTarget(project); - ExecutionEnvironmentBuilder builder = new ExecutionEnvironmentBuilder(project, myExecutor); - ProgramRunner runner = ProgramRunnerUtil.getRunner(myExecutor.getId(), configuration); - if (runner == null) { + RunnerAndConfigurationSettings configuration = getConfiguration(project); + ExecutionEnvironmentBuilder builder = configuration == null ? null : ExecutionEnvironmentBuilder.createOrNull(myExecutor, configuration); + if (builder == null) { return; } - - builder.setDataContext(dataContext).setTarget(target).setRunnerAndSettings(runner, configuration); - ExecutionManager.getInstance(project).restartRunProfile(runner, builder.build(), null); + ExecutionManager.getInstance(project).restartRunProfile(builder.activeTarget().dataContext(e.getDataContext()).build()); } } } diff --git a/platform/lang-impl/src/com/intellij/execution/ProgramRunnerUtil.java b/platform/lang-impl/src/com/intellij/execution/ProgramRunnerUtil.java index b27a939dd57c..5ad5f73b954a 100644 --- a/platform/lang-impl/src/com/intellij/execution/ProgramRunnerUtil.java +++ b/platform/lang-impl/src/com/intellij/execution/ProgramRunnerUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,23 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.intellij.execution; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.RunConfiguration; -import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.impl.RunDialog; import com.intellij.execution.impl.RunManagerImpl; +import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ExecutionEnvironmentBuilder; import com.intellij.execution.runners.ExecutionUtil; import com.intellij.execution.runners.ProgramRunner; -import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.icons.AllIcons; import com.intellij.internal.statistic.UsageTrigger; import com.intellij.internal.statistic.beans.ConvertUsagesUtil; -import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; @@ -41,11 +38,8 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; -/** - * @author spleaner - */ public class ProgramRunnerUtil { - private static final Logger LOG = Logger.getInstance("#com.intellij.execution.ProgramRunnerUtil"); + private static final Logger LOG = Logger.getInstance(ProgramRunnerUtil.class); private ProgramRunnerUtil() { } @@ -55,102 +49,82 @@ public class ProgramRunnerUtil { return configuration == null ? null : RunnerRegistry.getInstance().getRunner(executorId, configuration.getConfiguration()); } - public static void executeConfiguration(@NotNull final Project project, - @Nullable final DataContext context, - @NotNull final RunnerAndConfigurationSettings configuration, - @NotNull final Executor executor, - @NotNull final ExecutionTarget target, - @Nullable RunContentDescriptor contentToReuse, - final boolean showSettings) { - ProgramRunner runner = getRunner(executor.getId(), configuration); - if (runner == null) { - LOG.error("Runner MUST not be null! Cannot find runner for " + - executor.getId() + - " and " + - configuration.getConfiguration().getFactory().getName()); - return; - } - executeConfiguration(project, context, configuration, executor, target, contentToReuse, showSettings, runner, null, true); - } - - public static void executeConfiguration(Project project, - @Nullable DataContext context, - @Nullable RunnerAndConfigurationSettings configuration, - Executor executor, - ExecutionTarget target, - RunContentDescriptor contentToReuse, - boolean showSettings, - @NotNull ProgramRunner runner, - @Nullable RunProfile runProfile, - boolean assignNewId) { - if (ExecutorRegistry.getInstance().isStarting(project, executor.getId(), runner.getRunnerId())) { - return; - } - - if (configuration != null && !ExecutionTargetManager.canRun(configuration, target)) { - ExecutionUtil.handleExecutionError( - project, executor.getToolWindowId(), configuration.getConfiguration(), - new ExecutionException(StringUtil.escapeXml("Cannot run '" + configuration.getName() + "' on '" + target.getDisplayName() + "'"))); + public static void executeConfiguration(@NotNull ExecutionEnvironment environment, boolean showSettings, boolean assignNewId) { + if (ExecutorRegistry.getInstance().isStarting(environment)) { return; } - if (configuration != null && - (!RunManagerImpl.canRunConfiguration(configuration, executor) || (showSettings && configuration.isEditBeforeRun()))) { - if (!RunDialog.editConfiguration(project, configuration, "Edit configuration", executor)) { + RunnerAndConfigurationSettings runnerAndConfigurationSettings = environment.getRunnerAndConfigurationSettings(); + if (runnerAndConfigurationSettings != null) { + if (!ExecutionTargetManager.canRun(environment)) { + ExecutionUtil.handleExecutionError(environment, new ExecutionException( + StringUtil.escapeXml("Cannot run '" + environment.getRunProfile().getName() + "' on '" + environment.getExecutionTarget().getDisplayName() + "'"))); return; } - while (!RunManagerImpl.canRunConfiguration(configuration, executor)) { - if (Messages.YES == Messages - .showYesNoDialog(project, "Configuration is still incorrect. Do you want to edit it again?", "Change Configuration Settings", - "Edit", "Continue Anyway", Messages.getErrorIcon())) { - if (!RunDialog.editConfiguration(project, configuration, "Edit configuration", executor)) { - return; - } + if (!RunManagerImpl.canRunConfiguration(environment) || (showSettings && runnerAndConfigurationSettings.isEditBeforeRun())) { + if (!RunDialog.editConfiguration(environment, "Edit configuration")) { + return; } - else { - break; + + while (!RunManagerImpl.canRunConfiguration(environment)) { + if (Messages.YES == Messages + .showYesNoDialog(environment.getProject(), "Configuration is still incorrect. Do you want to edit it again?", "Change Configuration Settings", + "Edit", "Continue Anyway", Messages.getErrorIcon())) { + if (!RunDialog.editConfiguration(environment, "Edit configuration")) { + return; + } + } + else { + break; + } } } - } - final ConfigurationType configurationType = configuration != null ? configuration.getType() : null; - if (configurationType != null) { - UsageTrigger.trigger("execute." + ConvertUsagesUtil.ensureProperKey(configurationType.getId()) + "." + executor.getId()); + ConfigurationType configurationType = runnerAndConfigurationSettings.getType(); + if (configurationType != null) { + UsageTrigger.trigger("execute." + ConvertUsagesUtil.ensureProperKey(configurationType.getId()) + "." + environment.getExecutor().getId()); + } } try { - ExecutionEnvironmentBuilder builder = - new ExecutionEnvironmentBuilder(project, executor); - if (configuration != null) { - builder.setRunnerAndSettings(runner, configuration); - } - else { - builder.setRunnerId(runner.getRunnerId()); - } - builder.setTarget(target).setContentToReuse(contentToReuse).setDataContext(context); if (assignNewId) { - builder.assignNewId(); - } - if (runProfile != null) { - builder.setRunProfile(runProfile); + environment.assignNewExecutionId(); } - runner.execute(builder.build()); + environment.getRunner().execute(environment); } catch (ExecutionException e) { - String name = configuration != null ? configuration.getName() : null; - if (name == null && runProfile != null) name = runProfile.getName(); - if (name == null && contentToReuse != null) name = contentToReuse.getDisplayName(); - if (name == null) name = "<Unknown>"; - ExecutionUtil.handleExecutionError(project, executor.getToolWindowId(), name, e); + String name = runnerAndConfigurationSettings != null ? runnerAndConfigurationSettings.getName() : null; + if (name == null) { + name = environment.getRunProfile().getName(); + } + if (name == null && environment.getContentToReuse() != null) { + name = environment.getContentToReuse().getDisplayName(); + } + if (name == null) { + name = "<Unknown>"; + } + ExecutionUtil.handleExecutionError(environment.getProject(), environment.getExecutor().getToolWindowId(), name, e); } } - public static void executeConfiguration(@NotNull Project project, @NotNull RunnerAndConfigurationSettings configuration, @NotNull Executor executor) { - executeConfiguration(project, null, configuration, executor, ExecutionTargetManager.getActiveTarget(project), null, true); + ExecutionEnvironmentBuilder builder; + try { + builder = ExecutionEnvironmentBuilder.create(executor, configuration); + } + catch (ExecutionException e) { + LOG.error(e); + return; + } + + executeConfiguration(builder + .contentToReuse(null) + .dataContext(null) + .activeTarget() + .build(), true, true); } public static Icon getConfigurationIcon(final RunnerAndConfigurationSettings settings, diff --git a/platform/lang-impl/src/com/intellij/execution/actions/ChooseRunConfigurationPopup.java b/platform/lang-impl/src/com/intellij/execution/actions/ChooseRunConfigurationPopup.java index 1a0235ac9d46..a4764dae0036 100644 --- a/platform/lang-impl/src/com/intellij/execution/actions/ChooseRunConfigurationPopup.java +++ b/platform/lang-impl/src/com/intellij/execution/actions/ChooseRunConfigurationPopup.java @@ -22,8 +22,8 @@ import com.intellij.execution.configurations.UnknownConfigurationType; import com.intellij.execution.impl.EditConfigurationsDialog; import com.intellij.execution.impl.RunDialog; import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl; +import com.intellij.execution.runners.ExecutionUtil; import com.intellij.execution.runners.ProgramRunner; -import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.util.PropertiesComponent; @@ -193,10 +193,7 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { } private void updatePresentation() { - final Executor executor = getExecutor(); - if (executor != null) { - myPopup.setCaption(executor.getActionName()); - } + myPopup.setCaption(getExecutor().getActionName()); } static void execute(final ItemWrapper itemWrapper, final Executor executor) { @@ -218,12 +215,10 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { void editConfiguration(@NotNull final Project project, @NotNull final RunnerAndConfigurationSettings configuration) { final Executor executor = getExecutor(); - assert executor != null; - PropertiesComponent.getInstance().setValue("run.configuration.edit.ad", Boolean.toString(true)); if (RunDialog.editConfiguration(project, configuration, "Edit configuration settings", executor)) { RunManagerEx.getInstanceEx(project).setSelectedConfiguration(configuration); - doRunConfiguration(configuration, executor, project); + ExecutionUtil.runConfiguration(configuration, executor); } } @@ -379,7 +374,7 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { public void perform(@NotNull Project project, @NotNull Executor executor, @NotNull DataContext context) { RunnerAndConfigurationSettings config = getValue(); RunManagerEx.getInstanceEx(project).setSelectedConfiguration(config); - doRunConfiguration(config, executor, project); + ExecutionUtil.runConfiguration(config, executor); } @Override @@ -404,7 +399,7 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { @Override public boolean available(Executor executor) { - return null != ProgramRunnerUtil.getRunner(executor.getId(), getValue()); + return ProgramRunnerUtil.getRunner(executor.getId(), getValue()) != null; } @Override @@ -462,7 +457,7 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { final List<ItemWrapper> configurations = getValues(); final int index = configurations.indexOf(value); if (index > 0 && index <= configurations.size() - 1) { - final ItemWrapper aboveConfiguration = index == 0 ? null : configurations.get(index - 1); + final ItemWrapper aboveConfiguration = configurations.get(index - 1); if (aboveConfiguration != null && aboveConfiguration.isDynamic() != value.isDynamic()) { return new ListSeparator(); @@ -508,18 +503,15 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { } } - final Executor executor = myAction.getExecutor(); - assert executor != null; - - if (finalChoice && wrapper.available(executor)) { + if (finalChoice && wrapper.available(myAction.getExecutor())) { return doFinalStep(new Runnable() { @Override public void run() { - if (executor == myAction.myAlternativeExecutor) { + if (myAction.getExecutor() == myAction.myAlternativeExecutor) { PropertiesComponent.getInstance().setValue(myAction.myAddKey, Boolean.toString(true)); } - wrapper.perform(myProject, executor, DataManager.getInstance().getDataContext()); + wrapper.perform(myProject, myAction.getExecutor(), DataManager.getInstance().getDataContext()); } }); } @@ -545,14 +537,6 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { } } - private static void doRunConfiguration(RunnerAndConfigurationSettings configuration, Executor executor, Project project) { - ExecutionManager.getInstance(project).restartRunProfile(project, - executor, - ExecutionTargetManager.getActiveTarget(project), - configuration, - (RunContentDescriptor)null); - } - private static final class ConfigurationActionsStep extends BaseListPopupStep<ActionWrapper> { @NotNull private final RunnerAndConfigurationSettings mySettings; @@ -600,11 +584,13 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { @Override public void perform() { final RunManagerEx manager = RunManagerEx.getInstanceEx(project); - if (dynamic) manager.setTemporaryConfiguration(settings); + if (dynamic) { + manager.setTemporaryConfiguration(settings); + } manager.setSelectedConfiguration(settings); ExecutionTargetManager.setActiveTarget(project, eachTarget); - doRunConfiguration(settings, action.getExecutor(), project); + ExecutionUtil.runConfiguration(settings, action.getExecutor()); } }); } @@ -617,9 +603,11 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { @Override public void perform() { final RunManagerEx manager = RunManagerEx.getInstanceEx(project); - if (dynamic) manager.setTemporaryConfiguration(settings); + if (dynamic) { + manager.setTemporaryConfiguration(settings); + } manager.setSelectedConfiguration(settings); - doRunConfiguration(settings, executor, project); + ExecutionUtil.runConfiguration(settings, executor); } }); isFirst = false; @@ -857,7 +845,7 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { RunnerAndConfigurationSettings selectedConfiguration = RunManagerEx.getInstanceEx(project).getSelectedConfiguration(); if (myConfigurations.contains(selectedConfiguration)) { RunManagerEx.getInstanceEx(project).setSelectedConfiguration(selectedConfiguration); - doRunConfiguration(selectedConfiguration, myExecutorProvider.getExecutor(), project); + ExecutionUtil.runConfiguration(selectedConfiguration, myExecutorProvider.getExecutor()); } } @@ -906,8 +894,7 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { public void run() { RunnerAndConfigurationSettings settings = selectedValue.getSettings(); RunManagerEx.getInstanceEx(myProject).setSelectedConfiguration(settings); - doRunConfiguration(settings, myExecutorProvider.getExecutor(), myProject); - + ExecutionUtil.runConfiguration(settings, myExecutorProvider.getExecutor()); } }); } else { @@ -961,7 +948,7 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { @Override public void perform(@NotNull final Project project, @NotNull final Executor executor, @NotNull DataContext context) { ExecutionTargetManager.setActiveTarget(project, eachTarget); - doRunConfiguration(selectedConfiguration, executor, project); + ExecutionUtil.runConfiguration(selectedConfiguration, executor); } @Override @@ -1035,7 +1022,7 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { - doRunConfiguration(RunManager.getInstance(project).getSelectedConfiguration(), executor, project); + ExecutionUtil.runConfiguration(RunManager.getInstance(project).getSelectedConfiguration(), executor); } }); } @@ -1116,7 +1103,7 @@ public class ChooseRunConfigurationPopup implements ExecutorProvider { public void perform(@NotNull Project project, @NotNull Executor executor, @NotNull DataContext context) { manager.setTemporaryConfiguration(configuration); RunManagerEx.getInstanceEx(project).setSelectedConfiguration(configuration); - doRunConfiguration(configuration, executor, project); + ExecutionUtil.runConfiguration(configuration, executor); } @Override diff --git a/platform/lang-impl/src/com/intellij/execution/actions/RunContextAction.java b/platform/lang-impl/src/com/intellij/execution/actions/RunContextAction.java index f5741242089d..0a467c7cec23 100644 --- a/platform/lang-impl/src/com/intellij/execution/actions/RunContextAction.java +++ b/platform/lang-impl/src/com/intellij/execution/actions/RunContextAction.java @@ -18,10 +18,9 @@ package com.intellij.execution.actions; import com.intellij.execution.*; import com.intellij.execution.configurations.RunConfiguration; +import com.intellij.execution.runners.ExecutionUtil; import com.intellij.execution.runners.ProgramRunner; -import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.openapi.actionSystem.Presentation; -import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -47,12 +46,8 @@ public class RunContextAction extends BaseRunConfigurationAction { runManager.setTemporaryConfiguration(configuration); } runManager.setSelectedConfiguration(configuration); - Project project = context.getProject(); - ExecutionManager.getInstance(project).restartRunProfile(project, - myExecutor, - ExecutionTargetManager.getActiveTarget(project), - configuration, - (RunContentDescriptor)null); + + ExecutionUtil.runConfiguration(configuration, myExecutor); } @Override @@ -81,11 +76,10 @@ public class RunContextAction extends BaseRunConfigurationAction { configuration = context.getConfiguration(); } - if (configuration == null) return Pair.create(false, false); - - final ProgramRunner runner = getRunner(configuration.getConfiguration()); - if (runner == null) return Pair.create(false, false); - + ProgramRunner runner = configuration == null ? null : getRunner(configuration.getConfiguration()); + if (runner == null) { + return Pair.create(false, false); + } return Pair.create(!ExecutorRegistry.getInstance().isStarting(context.getProject(), myExecutor.getId(), runner.getRunnerId()), true); } } diff --git a/platform/lang-impl/src/com/intellij/execution/actions/StopAction.java b/platform/lang-impl/src/com/intellij/execution/actions/StopAction.java index 618a4b1c65c5..75466528ae2f 100644 --- a/platform/lang-impl/src/com/intellij/execution/actions/StopAction.java +++ b/platform/lang-impl/src/com/intellij/execution/actions/StopAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.intellij.execution.actions; +import com.intellij.execution.ExecutionBundle; import com.intellij.execution.ExecutionManager; import com.intellij.execution.KillableProcess; +import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.ui.RunContentDescriptor; -import com.intellij.execution.ui.RunContentManager; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.progress.ProgressIndicator; @@ -29,7 +29,7 @@ import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; -import com.intellij.openapi.ui.popup.ListItemDescriptor; +import com.intellij.openapi.ui.popup.ListItemDescriptorAdapter; import com.intellij.openapi.ui.popup.PopupChooserBuilder; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Pair; @@ -49,19 +49,20 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -public class StopAction extends DumbAwareAction implements AnAction.TransparentUpdate { +class StopAction extends DumbAwareAction implements AnAction.TransparentUpdate { @Override public void update(final AnActionEvent e) { boolean enable = false; Icon icon = getTemplatePresentation().getIcon(); String description = getTemplatePresentation().getDescription(); - final Presentation presentation = e.getPresentation(); - + Presentation presentation = e.getPresentation(); if (ActionPlaces.MAIN_MENU.equals(e.getPlace())) { enable = !getCancellableProcesses(e.getProject()).isEmpty() || !getActiveDescriptors(e.getDataContext()).isEmpty(); + presentation.setText(getTemplatePresentation().getText()); } else { - final ProcessHandler processHandler = getHandler(e.getDataContext()); + RunContentDescriptor contentDescriptor = e.getData(LangDataKeys.RUN_CONTENT_DESCRIPTOR); + ProcessHandler processHandler = contentDescriptor == null ? null : contentDescriptor.getProcessHandler(); if (processHandler != null && !processHandler.isProcessTerminated()) { if (!processHandler.isProcessTerminating()) { enable = true; @@ -72,6 +73,14 @@ public class StopAction extends DumbAwareAction implements AnAction.TransparentU description = "Kill process"; } } + + RunProfile runProfile = e.getData(LangDataKeys.RUN_PROFILE); + if (runProfile == null && contentDescriptor == null) { + presentation.setText(getTemplatePresentation().getText()); + } + else { + presentation.setText(ExecutionBundle.message("stop.configuration.action.name", runProfile == null ? contentDescriptor.getDisplayName() : runProfile.getName())); + } } presentation.setEnabled(enable); @@ -84,7 +93,8 @@ public class StopAction extends DumbAwareAction implements AnAction.TransparentU final DataContext dataContext = e.getDataContext(); ProcessHandler activeProcessHandler = getHandler(dataContext); - List<Pair<TaskInfo, ProgressIndicator>> backgroundTasks = getCancellableProcesses(e.getProject()); + Project project = e.getProject(); + List<Pair<TaskInfo, ProgressIndicator>> backgroundTasks = getCancellableProcesses(project); if (ActionPlaces.MAIN_MENU.equals(e.getPlace())) { if (activeProcessHandler != null && !activeProcessHandler.isProcessTerminating() && !activeProcessHandler.isProcessTerminated() && backgroundTasks.isEmpty()) { @@ -94,12 +104,14 @@ public class StopAction extends DumbAwareAction implements AnAction.TransparentU Pair<List<HandlerItem>, HandlerItem> handlerItems = getItemsList(backgroundTasks, getActiveDescriptors(dataContext), activeProcessHandler); - if (handlerItems.first.isEmpty()) return; + if (handlerItems == null || handlerItems.first.isEmpty()) { + return; + } final JBList list = new JBList(handlerItems.first); if (handlerItems.second != null) list.setSelectedValue(handlerItems.second, true); - list.setCellRenderer(new GroupedItemsListRenderer(new ListItemDescriptor() { + list.setCellRenderer(new GroupedItemsListRenderer(new ListItemDescriptorAdapter() { @Nullable @Override public String getTextFor(Object value) { @@ -108,12 +120,6 @@ public class StopAction extends DumbAwareAction implements AnAction.TransparentU @Nullable @Override - public String getTooltipFor(Object value) { - return null; - } - - @Nullable - @Override public Icon getIconFor(Object value) { return value instanceof HandlerItem ? ((HandlerItem)value).icon : null; } @@ -122,12 +128,6 @@ public class StopAction extends DumbAwareAction implements AnAction.TransparentU public boolean hasSeparatorAboveOf(Object value) { return value instanceof HandlerItem && ((HandlerItem)value).hasSeparator; } - - @Nullable - @Override - public String getCaptionAboveOf(Object value) { - return null; - } })); final PopupChooserBuilder builder = JBPopupFactory.getInstance().createListPopupBuilder(list); @@ -148,7 +148,8 @@ public class StopAction extends DumbAwareAction implements AnAction.TransparentU } }).setRequestFocus(true).createPopup(); - popup.showCenteredInCurrentWindow(e.getProject()); + assert project != null; + popup.showCenteredInCurrentWindow(project); } else { if (activeProcessHandler != null) { @@ -171,12 +172,15 @@ public class StopAction extends DumbAwareAction implements AnAction.TransparentU }); } + @Nullable private static Pair<List<HandlerItem>, HandlerItem> getItemsList(List<Pair<TaskInfo, ProgressIndicator>> tasks, List<RunContentDescriptor> descriptors, ProcessHandler activeProcessHandler) { - if (tasks.isEmpty() && descriptors.isEmpty()) return Pair.create(Collections.<HandlerItem>emptyList(), null); + if (tasks.isEmpty() && descriptors.isEmpty()) { + return null; + } - ArrayList<HandlerItem> items = new ArrayList<HandlerItem>(tasks.size() + descriptors.size()); + List<HandlerItem> items = new ArrayList<HandlerItem>(tasks.size() + descriptors.size()); HandlerItem selected = null; for (RunContentDescriptor descriptor : descriptors) { final ProcessHandler handler = descriptor.getProcessHandler(); @@ -188,7 +192,9 @@ public class StopAction extends DumbAwareAction implements AnAction.TransparentU } }; items.add(item); - if (handler == activeProcessHandler) selected = item; + if (handler == activeProcessHandler) { + selected = item; + } } } @@ -202,7 +208,7 @@ public class StopAction extends DumbAwareAction implements AnAction.TransparentU }); hasSeparator = false; } - return Pair.<List<HandlerItem>, HandlerItem>create(items, selected); + return Pair.create(items, selected); } private static void stopProcess(ProcessHandler processHandler) { @@ -220,21 +226,19 @@ public class StopAction extends DumbAwareAction implements AnAction.TransparentU } @Nullable - static ProcessHandler getHandler(final DataContext dataContext) { - final RunContentDescriptor contentDescriptor = RunContentManager.RUN_CONTENT_DESCRIPTOR.getData(dataContext); - final ProcessHandler processHandler; + static ProcessHandler getHandler(@NotNull DataContext dataContext) { + final RunContentDescriptor contentDescriptor = LangDataKeys.RUN_CONTENT_DESCRIPTOR.getData(dataContext); if (contentDescriptor != null) { // toolwindow case - processHandler = contentDescriptor.getProcessHandler(); + return contentDescriptor.getProcessHandler(); } else { // main menu toolbar final Project project = CommonDataKeys.PROJECT.getData(dataContext); final RunContentDescriptor selectedContent = project == null ? null : ExecutionManager.getInstance(project).getContentManager().getSelectedContent(); - processHandler = selectedContent == null ? null : selectedContent.getProcessHandler(); + return selectedContent == null ? null : selectedContent.getProcessHandler(); } - return processHandler; } @NotNull diff --git a/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java b/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java index 1a9afd1e25e5..d7f40f35a219 100644 --- a/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java @@ -616,7 +616,7 @@ public class LanguageConsoleImpl implements Disposable, TypeSafeDataProvider { sink.put(OpenFileDescriptor.NAVIGATE_IN_EDITOR, myConsoleEditor); } else if (getProject().isInitialized()) { - sink.put(key, FileEditorManagerEx.getInstanceEx(getProject()).getData(key.getName(), myConsoleEditor, myVirtualFile)); + sink.put(key, FileEditorManagerEx.getInstanceEx(getProject()).getData(key.getName(), myConsoleEditor, myConsoleEditor.getCaretModel().getCurrentCaret())); } } diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditor.java b/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditor.java index bdae21f781ea..7bae2105014a 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditor.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditor.java @@ -75,16 +75,14 @@ class ConfigurationSettingsEditor extends CompositeSettingsEditor<RunnerAndConfi myRunnersComponent = new RunnersEditorComponent(); - ProgramRunner[] runners = RunnerRegistry.getInstance().getRegisteredRunners(); final Executor[] executors = ExecutorRegistry.getInstance().getRegisteredExecutors(); for (final Executor executor : executors) { - for (ProgramRunner runner : runners) { - if (runner.canRun(executor.getId(), myConfiguration)) { - JComponent perRunnerSettings = createCompositePerRunnerSettings(executor, runner); - if (perRunnerSettings != null) { - myRunnersComponent.addExecutorComponent(executor, perRunnerSettings); - } + ProgramRunner runner = RunnerRegistry.getInstance().getRunner(executor.getId(), myConfiguration); + if (runner != null) { + JComponent perRunnerSettings = createCompositePerRunnerSettings(executor, runner); + if (perRunnerSettings != null) { + myRunnersComponent.addExecutorComponent(executor, perRunnerSettings); } } } diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.java index c017284f8e11..29808af0845d 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/ExecutionManagerImpl.java @@ -13,13 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.intellij.execution.impl; import com.intellij.CommonBundle; import com.intellij.execution.*; import com.intellij.execution.configuration.CompatibilityAwareRunProfile; -import com.intellij.execution.configurations.*; +import com.intellij.execution.configurations.RunConfiguration; +import com.intellij.execution.configurations.RunProfile; +import com.intellij.execution.configurations.RunProfileState; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; @@ -34,12 +35,12 @@ import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.impl.SimpleDataContext; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Trinity; @@ -47,21 +48,20 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.ui.docking.DockManager; import com.intellij.util.Alarm; +import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.containers.Predicate; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; -/** - * @author dyoma - */ -public class ExecutionManagerImpl extends ExecutionManager implements ProjectComponent { +public class ExecutionManagerImpl extends ExecutionManager implements Disposable { public static final Key<Object> EXECUTION_SESSION_ID_KEY = Key.create("EXECUTION_SESSION_ID_KEY"); - private static final Logger LOG = Logger.getInstance("com.intellij.execution.impl.ExecutionManagerImpl"); + + private static final Logger LOG = Logger.getInstance(ExecutionManagerImpl.class); + private static final ProcessHandler[] EMPTY_PROCESS_HANDLERS = new ProcessHandler[0]; private final Project myProject; @@ -70,28 +70,12 @@ public class ExecutionManagerImpl extends ExecutionManager implements ProjectCom private final List<Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor>> myRunningConfigurations = ContainerUtil.createLockFreeCopyOnWriteList(); - /** - * reflection - */ - ExecutionManagerImpl(final Project project) { + ExecutionManagerImpl(@NotNull Project project) { myProject = project; } @Override - public void projectOpened() { - ((RunContentManagerImpl)getContentManager()).init(); - } - - @Override - public void projectClosed() { - } - - @Override - public void initComponent() { - } - - @Override - public void disposeComponent() { + public void dispose() { for (Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity : myRunningConfigurations) { Disposer.dispose(trinity.first); } @@ -108,112 +92,118 @@ public class ExecutionManagerImpl extends ExecutionManager implements ProjectCom return myContentManager; } + @NotNull @Override public ProcessHandler[] getRunningProcesses() { - final List<ProcessHandler> handlers = new ArrayList<ProcessHandler>(); + if (myContentManager == null) return EMPTY_PROCESS_HANDLERS; + List<ProcessHandler> handlers = null; for (RunContentDescriptor descriptor : getContentManager().getAllDescriptors()) { - final ProcessHandler processHandler = descriptor.getProcessHandler(); + ProcessHandler processHandler = descriptor.getProcessHandler(); if (processHandler != null) { + if (handlers == null) { + handlers = new SmartList<ProcessHandler>(); + } handlers.add(processHandler); } } - return handlers.toArray(new ProcessHandler[handlers.size()]); + return handlers == null ? EMPTY_PROCESS_HANDLERS : handlers.toArray(new ProcessHandler[handlers.size()]); } @Override public void compileAndRun(@NotNull final Runnable startRunnable, - @NotNull final ExecutionEnvironment env, + @NotNull final ExecutionEnvironment environment, @Nullable final RunProfileState state, @Nullable final Runnable onCancelRunnable) { - long id = env.getExecutionId(); + long id = environment.getExecutionId(); if (id == 0) { - id = env.assignNewExecutionId(); + id = environment.assignNewExecutionId(); } - RunProfile profile = env.getRunProfile(); - - if (profile instanceof RunConfiguration) { - final RunConfiguration runConfiguration = (RunConfiguration)profile; - final RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(myProject); - final List<BeforeRunTask> activeTasks = new ArrayList<BeforeRunTask>(); - activeTasks.addAll(runManager.getBeforeRunTasks(runConfiguration)); + RunProfile profile = environment.getRunProfile(); + if (!(profile instanceof RunConfiguration)) { + startRunnable.run(); + return; + } - DataContext context = env.getDataContext(); + final RunConfiguration runConfiguration = (RunConfiguration)profile; + final List<BeforeRunTask> beforeRunTasks = RunManagerEx.getInstanceEx(myProject).getBeforeRunTasks(runConfiguration); + if (beforeRunTasks.isEmpty()) { + startRunnable.run(); + } + else { + DataContext context = environment.getDataContext(); final DataContext projectContext = context != null ? context : SimpleDataContext.getProjectContext(myProject); - - if (!activeTasks.isEmpty()) { - final long finalId = id; - final Long executionSessionId = new Long(id); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - /** @noinspection SSBasedInspection*/ - @Override - public void run() { - for (BeforeRunTask task : activeTasks) { - if (myProject.isDisposed()) { - return; - } - BeforeRunTaskProvider<BeforeRunTask> provider = BeforeRunTaskProvider.getProvider(myProject, task.getProviderId()); - if (provider == null) { - LOG.warn("Cannot find BeforeRunTaskProvider for id='" + task.getProviderId() + "'"); - continue; - } - ExecutionEnvironment taskEnvironment = new ExecutionEnvironmentBuilder(env).setContentToReuse(null).build(); - taskEnvironment.setExecutionId(finalId); - EXECUTION_SESSION_ID_KEY.set(taskEnvironment, executionSessionId); - if (!provider.executeTask(projectContext, runConfiguration, taskEnvironment, task)) { - if (onCancelRunnable != null) { - SwingUtilities.invokeLater(onCancelRunnable); - } - return; - } + final long finalId = id; + final Long executionSessionId = new Long(id); + ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { + /** @noinspection SSBasedInspection*/ + @Override + public void run() { + for (BeforeRunTask task : beforeRunTasks) { + if (myProject.isDisposed()) { + return; } - // important! Do not use DumbService.smartInvokelater here because it depends on modality state - // and execution of startRunnable could be skipped if modality state check fails - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - if (!myProject.isDisposed()) { - DumbService.getInstance(myProject).runWhenSmart(startRunnable); - } + @SuppressWarnings("unchecked") + BeforeRunTaskProvider<BeforeRunTask> provider = BeforeRunTaskProvider.getProvider(myProject, task.getProviderId()); + if (provider == null) { + LOG.warn("Cannot find BeforeRunTaskProvider for id='" + task.getProviderId() + "'"); + continue; + } + ExecutionEnvironment taskEnvironment = new ExecutionEnvironmentBuilder(environment).contentToReuse(null).build(); + taskEnvironment.setExecutionId(finalId); + EXECUTION_SESSION_ID_KEY.set(taskEnvironment, executionSessionId); + if (!provider.executeTask(projectContext, runConfiguration, taskEnvironment, task)) { + if (onCancelRunnable != null) { + SwingUtilities.invokeLater(onCancelRunnable); } - }); + return; + } } - }); - } - else { - startRunnable.run(); - } - } - else { - startRunnable.run(); + // important! Do not use DumbService.smartInvokeLater here because it depends on modality state + // and execution of startRunnable could be skipped if modality state check fails + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + if (!myProject.isDisposed()) { + DumbService.getInstance(myProject).runWhenSmart(startRunnable); + } + } + }); + } + }); } } @Override - public void startRunProfile(@NotNull final RunProfileStarter starter, @NotNull final RunProfileState state, - @NotNull final Project project, @NotNull final Executor executor, @NotNull final ExecutionEnvironment env) { - final RunContentDescriptor reuseContent = - ExecutionManager.getInstance(project).getContentManager().getReuseContent(env); + public void startRunProfile(@NotNull final RunProfileStarter starter, + @NotNull final RunProfileState state, + @NotNull final ExecutionEnvironment environment) { + final Project project = environment.getProject(); + final RunContentDescriptor reuseContent = getContentManager().getReuseContent(environment); if (reuseContent != null) { - reuseContent.setExecutionId(env.getExecutionId()); + reuseContent.setExecutionId(environment.getExecutionId()); } - final RunProfile profile = env.getRunProfile(); - project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStartScheduled(executor.getId(), env); + final Executor executor = environment.getExecutor(); + project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStartScheduled(executor.getId(), environment); Runnable startRunnable = new Runnable() { @Override public void run() { - if (project.isDisposed()) return; + if (project.isDisposed()) { + return; + } + + RunProfile profile = environment.getRunProfile(); boolean started = false; try { - project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStarting(executor.getId(), env); - - final RunContentDescriptor descriptor = starter.execute(project, executor, state, reuseContent, env); + project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStarting(executor.getId(), environment); + final RunContentDescriptor descriptor = starter.execute(project, executor, state, reuseContent, environment); if (descriptor != null) { + environment.setContentToReuse(descriptor); final Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity = - Trinity.create(descriptor, env.getRunnerAndConfigurationSettings(), executor); + Trinity.create(descriptor, environment.getRunnerAndConfigurationSettings(), executor); myRunningConfigurations.add(trinity); Disposer.register(descriptor, new Disposable() { @Override @@ -221,13 +211,13 @@ public class ExecutionManagerImpl extends ExecutionManager implements ProjectCom myRunningConfigurations.remove(trinity); } }); - ExecutionManager.getInstance(project).getContentManager().showRunContent(executor, descriptor, reuseContent); + getContentManager().showRunContent(executor, descriptor, reuseContent); final ProcessHandler processHandler = descriptor.getProcessHandler(); if (processHandler != null) { if (!processHandler.isStartNotified()) { processHandler.startNotify(); } - project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStarted(executor.getId(), env, processHandler); + project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStarted(executor.getId(), environment, processHandler); started = true; processHandler.addProcessListener(new ProcessExecutionListener(project, profile, processHandler)); } @@ -239,7 +229,7 @@ public class ExecutionManagerImpl extends ExecutionManager implements ProjectCom } finally { if (!started) { - project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), env); + project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), environment); } } } @@ -249,11 +239,11 @@ public class ExecutionManagerImpl extends ExecutionManager implements ProjectCom startRunnable.run(); } else { - compileAndRun(startRunnable, env, state, new Runnable() { + compileAndRun(startRunnable, environment, state, new Runnable() { @Override public void run() { if (!project.isDisposed()) { - project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), env); + project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), environment); } } }); @@ -261,26 +251,36 @@ public class ExecutionManagerImpl extends ExecutionManager implements ProjectCom } @Override - public void startRunProfile(@NotNull RunProfileStarter starter, @NotNull RunProfileState state, @NotNull ExecutionEnvironment env) { - startRunProfile(starter, state, env.getProject(), env.getExecutor(), env); - } - - @Override - public void restartRunProfile(@NotNull final Project project, - @NotNull final Executor executor, - @NotNull final ExecutionTarget target, - @Nullable final RunnerAndConfigurationSettings configuration, - @Nullable final ProcessHandler processHandler) { + public void restartRunProfile(@NotNull Project project, + @NotNull Executor executor, + @NotNull ExecutionTarget target, + @Nullable RunnerAndConfigurationSettings configuration, + @Nullable ProcessHandler processHandler) { + ExecutionEnvironmentBuilder builder = createEnvironmentBuilder(project, executor, configuration); if (processHandler != null) { for (RunContentDescriptor descriptor : getContentManager().getAllDescriptors()) { - final ProcessHandler handler = descriptor.getProcessHandler(); - if (handler == processHandler) { - restartRunProfile(project, null, null, null, null, null, executor, target, configuration, descriptor); - return; + if (descriptor.getProcessHandler() == processHandler) { + builder.contentToReuse(descriptor); + break; } } } - restartRunProfile(project, null, null, null, null, null, executor, target, configuration, null); + restartRunProfile(builder.target(target).build()); + } + + @NotNull + private static ExecutionEnvironmentBuilder createEnvironmentBuilder(@NotNull Project project, @NotNull Executor executor, @Nullable RunnerAndConfigurationSettings configuration) { + ExecutionEnvironmentBuilder builder = new ExecutionEnvironmentBuilder(project, executor); + + ProgramRunner runner = RunnerRegistry.getInstance().getRunner(executor.getId(), configuration != null ? configuration.getConfiguration() : null); + if (runner == null && configuration != null) { + LOG.error("Cannot find runner for " + configuration.getName()); + } + else if (runner != null) { + assert configuration != null; + builder.runnerAndSettings(runner, configuration); + } + return builder; } @Override @@ -289,123 +289,89 @@ public class ExecutionManagerImpl extends ExecutionManager implements ProjectCom @NotNull ExecutionTarget target, @Nullable RunnerAndConfigurationSettings configuration, @Nullable RunContentDescriptor currentDescriptor) { - restartRunProfile(project, null, null, null, null, null, executor, target, configuration, currentDescriptor); + ExecutionEnvironmentBuilder builder = createEnvironmentBuilder(project, executor, configuration); + restartRunProfile(builder.target(target).contentToReuse(currentDescriptor).build()); } @Override public void restartRunProfile(@Nullable ProgramRunner runner, @NotNull ExecutionEnvironment environment, @Nullable RunContentDescriptor currentDescriptor) { - restartRunProfile(environment.getProject(), - environment.getDataContext(), - runner, - environment.getRunProfile(), - environment.getRunnerSettings(), - environment.getConfigurationSettings(), - environment.getExecutor(), - environment.getExecutionTarget(), - environment.getRunnerAndConfigurationSettings(), currentDescriptor); + ExecutionEnvironmentBuilder builder = new ExecutionEnvironmentBuilder(environment).contentToReuse(currentDescriptor); + if (runner != null) { + builder.runner(runner); + } + restartRunProfile(builder.build()); } + public static boolean isProcessRunning(@Nullable RunContentDescriptor descriptor) { + ProcessHandler processHandler = descriptor == null ? null : descriptor.getProcessHandler(); + return processHandler != null && !processHandler.isProcessTerminated(); + } - private void restartRunProfile(@NotNull final Project project, - @Nullable final DataContext context, - @Nullable ProgramRunner r, - @Nullable final RunProfile runProfile, - @Nullable final RunnerSettings runnerSettings, - @Nullable final ConfigurationPerRunnerSettings configurationPerRunnerSettings, - @NotNull final Executor executor, - @NotNull final ExecutionTarget target, - @Nullable final RunnerAndConfigurationSettings configuration, - @Nullable final RunContentDescriptor currentDescriptor) { - final ProgramRunner runner = r != null ? - r : - RunnerRegistry.getInstance().getRunner(executor.getId(), - configuration != null && configuration.getConfiguration() != null - ? configuration.getConfiguration() - : runProfile - ); - if (configuration != null && runner == null) { - LOG.error("Cannot find runner for " + configuration.getName()); - return; - } - - final List<RunContentDescriptor> runningConfigurationsOfTheSameType = new ArrayList<RunContentDescriptor>(); - final List<RunContentDescriptor> runningIncompatibleConfigurations = new ArrayList<RunContentDescriptor>(); + @Override + public void restartRunProfile(@NotNull final ExecutionEnvironment environment) { + RunnerAndConfigurationSettings configuration = environment.getRunnerAndConfigurationSettings(); - if (configuration != null) { - runningIncompatibleConfigurations.addAll(getIncompatibleRunningDescriptors(configuration)); + List<RunContentDescriptor> runningIncompatible; + if (configuration == null) { + runningIncompatible = Collections.emptyList(); } + else { + runningIncompatible = getIncompatibleRunningDescriptors(configuration); + } + + RunContentDescriptor contentToReuse = environment.getContentToReuse(); + final List<RunContentDescriptor> runningOfTheSameType = new SmartList<RunContentDescriptor>(); if (configuration != null && configuration.isSingleton()) { - runningConfigurationsOfTheSameType.addAll(getRunningDescriptorsOfTheSameConfigType(configuration)); + runningOfTheSameType.addAll(getRunningDescriptorsOfTheSameConfigType(configuration)); } - else if (currentDescriptor != null) { - runningConfigurationsOfTheSameType.add(currentDescriptor); + else if (isProcessRunning(contentToReuse)) { + runningOfTheSameType.add(contentToReuse); } - final List<RunContentDescriptor> runningConfigurationsToStop = ContainerUtil.concat(runningConfigurationsOfTheSameType, - runningIncompatibleConfigurations); - if (!runningConfigurationsToStop.isEmpty()) { + List<RunContentDescriptor> runningToStop = ContainerUtil.concat(runningOfTheSameType, runningIncompatible); + if (!runningToStop.isEmpty()) { if (configuration != null) { - if (!runningConfigurationsOfTheSameType.isEmpty() - && (runningConfigurationsOfTheSameType.size() > 1 || - currentDescriptor == null || - runningConfigurationsOfTheSameType.get(0) != currentDescriptor) && - !userApprovesStopForSameTypeConfigurations(project, configuration.getName(), runningConfigurationsOfTheSameType.size())) { + if (!runningOfTheSameType.isEmpty() + && (runningOfTheSameType.size() > 1 || contentToReuse == null || runningOfTheSameType.get(0) != contentToReuse) && + !userApprovesStopForSameTypeConfigurations(environment.getProject(), configuration.getName(), runningOfTheSameType.size())) { return; } - if (!runningIncompatibleConfigurations.isEmpty() - && !userApprovesStopForIncompatibleConfigurations(myProject, configuration.getName(), runningIncompatibleConfigurations)) { + if (!runningIncompatible.isEmpty() + && !userApprovesStopForIncompatibleConfigurations(myProject, configuration.getName(), runningIncompatible)) { return; } } - for (RunContentDescriptor descriptor : runningConfigurationsToStop) { + + for (RunContentDescriptor descriptor : runningToStop) { stop(descriptor); } } - Runnable runnable = new Runnable() { + awaitingTerminationAlarm.addRequest(new Runnable() { @Override public void run() { - if (runner != null && ExecutorRegistry.getInstance().isStarting(project, executor.getId(), runner.getRunnerId())) { + if (ExecutorRegistry.getInstance().isStarting(environment)) { awaitingTerminationAlarm.addRequest(this, 100); return; } - for (RunContentDescriptor descriptor : runningConfigurationsOfTheSameType) { + + for (RunContentDescriptor descriptor : runningOfTheSameType) { ProcessHandler processHandler = descriptor.getProcessHandler(); if (processHandler != null && !processHandler.isProcessTerminated()) { awaitingTerminationAlarm.addRequest(this, 100); return; } } - start(project, context, runner, runProfile, runnerSettings, configurationPerRunnerSettings, configuration, executor, target, - currentDescriptor); + start(environment); } - }; - awaitingTerminationAlarm.addRequest(runnable, 50); + }, 50); } - private static void start(@NotNull Project project, - @Nullable DataContext context, - @Nullable ProgramRunner runner, - @Nullable RunProfile runProfile, - @Nullable RunnerSettings runnerSettings, - @Nullable ConfigurationPerRunnerSettings configurationPerRunnerSettings, - @Nullable RunnerAndConfigurationSettings configuration, - @NotNull Executor executor, - @NotNull ExecutionTarget target, - @Nullable RunContentDescriptor descriptor) { - Runnable restarter = descriptor != null ? descriptor.getRestarter() : null; - if (runner != null && runProfile != null) { - ProgramRunnerUtil.executeConfiguration(project, context, configuration, executor, target, descriptor, - configuration != null && configuration.isEditBeforeRun(), runner, runProfile, false); - } - else if (configuration != null) { - ProgramRunnerUtil.executeConfiguration(project, context, configuration, executor, target, descriptor, true); - } - else if (restarter != null) { - restarter.run(); - } + private static void start(@NotNull ExecutionEnvironment environment) { + RunnerAndConfigurationSettings settings = environment.getRunnerAndConfigurationSettings(); + ProgramRunnerUtil.executeConfiguration(environment, settings != null && settings.isEditBeforeRun(), true); } private static boolean userApprovesStopForSameTypeConfigurations(Project project, String configName, int instancesCount) { @@ -505,35 +471,36 @@ public class ExecutionManagerImpl extends ExecutionManager implements ProjectCom Messages.getQuestionIcon(), option) == Messages.OK; } - private List<RunContentDescriptor> getRunningDescriptorsOfTheSameConfigType( - @NotNull final RunnerAndConfigurationSettings configurationAndSettings) { - return getRunningDescriptors(new Predicate<RunnerAndConfigurationSettings>() { + @NotNull + private List<RunContentDescriptor> getRunningDescriptorsOfTheSameConfigType(@NotNull final RunnerAndConfigurationSettings configurationAndSettings) { + return getRunningDescriptors(new Condition<RunnerAndConfigurationSettings>() { @Override - public boolean apply(@Nullable RunnerAndConfigurationSettings runningConfigurationAndSettings) { + public boolean value(@Nullable RunnerAndConfigurationSettings runningConfigurationAndSettings) { return configurationAndSettings == runningConfigurationAndSettings; } }); } - private List<RunContentDescriptor> getIncompatibleRunningDescriptors( - @NotNull final RunnerAndConfigurationSettings configurationAndSettings) { + @NotNull + private List<RunContentDescriptor> getIncompatibleRunningDescriptors(@NotNull RunnerAndConfigurationSettings configurationAndSettings) { final RunConfiguration configurationToCheckCompatibility = configurationAndSettings.getConfiguration(); - return getRunningDescriptors(new Predicate<RunnerAndConfigurationSettings>() { + return getRunningDescriptors(new Condition<RunnerAndConfigurationSettings>() { @Override - public boolean apply(@Nullable RunnerAndConfigurationSettings runningConfigurationAndSettings) { - if (runningConfigurationAndSettings == null) return false; - RunConfiguration runningConfiguration = runningConfigurationAndSettings.getConfiguration(); - if (runningConfiguration == null || !(runningConfiguration instanceof CompatibilityAwareRunProfile)) return false; + public boolean value(@Nullable RunnerAndConfigurationSettings runningConfigurationAndSettings) { + RunConfiguration runningConfiguration = runningConfigurationAndSettings == null ? null : runningConfigurationAndSettings.getConfiguration(); + if (runningConfiguration == null || !(runningConfiguration instanceof CompatibilityAwareRunProfile)) { + return false; + } return ((CompatibilityAwareRunProfile)runningConfiguration).mustBeStoppedToRun(configurationToCheckCompatibility); } }); } - private List<RunContentDescriptor> getRunningDescriptors( - Predicate<RunnerAndConfigurationSettings> condition) { - List<RunContentDescriptor> result = new ArrayList<RunContentDescriptor>(); + @NotNull + private List<RunContentDescriptor> getRunningDescriptors(@NotNull Condition<RunnerAndConfigurationSettings> condition) { + List<RunContentDescriptor> result = new SmartList<RunContentDescriptor>(); for (Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity : myRunningConfigurations) { - if (condition.apply(trinity.getSecond())) { + if (condition.value(trinity.getSecond())) { ProcessHandler processHandler = trinity.getFirst().getProcessHandler(); if (processHandler != null && !processHandler.isProcessTerminating() && !processHandler.isProcessTerminated()) { result.add(trinity.getFirst()); @@ -543,30 +510,27 @@ public class ExecutionManagerImpl extends ExecutionManager implements ProjectCom return result; } - private static void stop(RunContentDescriptor runContentDescriptor) { - ProcessHandler processHandler = runContentDescriptor != null ? runContentDescriptor.getProcessHandler() : null; + private static void stop(@Nullable RunContentDescriptor descriptor) { + ProcessHandler processHandler = descriptor != null ? descriptor.getProcessHandler() : null; if (processHandler == null) { return; } + if (processHandler instanceof KillableProcess && processHandler.isProcessTerminating()) { ((KillableProcess)processHandler).killProcess(); return; } - if (processHandler.detachIsDefault()) { - processHandler.detachProcess(); - } - else { - processHandler.destroyProcess(); + if (!processHandler.isProcessTerminated()) { + if (processHandler.detachIsDefault()) { + processHandler.detachProcess(); + } + else { + processHandler.destroyProcess(); + } } } - @Override - @NotNull - public String getComponentName() { - return "ExecutionManager"; - } - private static class ProcessExecutionListener extends ProcessAdapter { private final Project myProject; private final RunProfile myProfile; diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ProjectRunConfigurationManager.java b/platform/lang-impl/src/com/intellij/execution/impl/ProjectRunConfigurationManager.java index deadaad0a0d1..42b9be79890e 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/ProjectRunConfigurationManager.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/ProjectRunConfigurationManager.java @@ -50,7 +50,7 @@ import java.util.Set; } ) public class ProjectRunConfigurationManager implements ProjectComponent, PersistentStateComponent<Element> { - private static final Logger LOG = Logger.getInstance("#com.intellij.execution.impl.ProjectRunConfigurationManager"); + private static final Logger LOG = Logger.getInstance(ProjectRunConfigurationManager.class); private final RunManagerImpl myManager; private List<Element> myUnloadedElements = null; @@ -150,7 +150,7 @@ public class ProjectRunConfigurationManager implements ProjectComponent, Persist } if (myUnloadedElements != null) { for (Element unloadedElement : myUnloadedElements) { - element.addContent((Element)unloadedElement.clone()); + element.addContent(unloadedElement.clone()); } } } diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java index edf1352a760c..97f36a8fd2b4 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurationBeforeRunProvider.java @@ -23,6 +23,7 @@ import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; +import com.intellij.execution.runners.ExecutionEnvironmentBuilder; import com.intellij.execution.runners.ProgramRunner; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; @@ -137,7 +138,7 @@ extends BeforeRunTaskProvider<RunConfigurationBeforeRunProvider.RunConfigurableB } @NotNull - private List<RunnerAndConfigurationSettings> getAvailableConfigurations(RunConfiguration runConfiguration) { + private static List<RunnerAndConfigurationSettings> getAvailableConfigurations(RunConfiguration runConfiguration) { Project project = runConfiguration.getProject(); if (project == null || !project.isInitialized()) return Collections.emptyList(); @@ -164,9 +165,7 @@ extends BeforeRunTaskProvider<RunConfigurationBeforeRunProvider.RunConfigurableB } String executorId = DefaultRunExecutor.getRunExecutorInstance().getId(); final ProgramRunner runner = ProgramRunnerUtil.getRunner(executorId, settings); - if (runner == null) - return false; - return runner.canRun(executorId, settings.getConfiguration()); + return runner != null && runner.canRun(executorId, settings.getConfiguration()); } @Override @@ -180,16 +179,17 @@ extends BeforeRunTaskProvider<RunConfigurationBeforeRunProvider.RunConfigurableB } final Executor executor = DefaultRunExecutor.getRunExecutorInstance(); final String executorId = executor.getId(); - final ProgramRunner runner = ProgramRunnerUtil.getRunner(executorId, settings); - if (runner == null) + ExecutionEnvironmentBuilder builder = ExecutionEnvironmentBuilder.createOrNull(executor, settings); + if (builder == null) { return false; - final ExecutionEnvironment environment = new ExecutionEnvironment(executor, runner, settings, myProject); + } + final ExecutionEnvironment environment = builder.build(); environment.setExecutionId(env.getExecutionId()); if (!ExecutionTargetManager.canRun(settings, env.getExecutionTarget())) { return false; } - if (!runner.canRun(executorId, environment.getRunProfile())) { + if (!environment.getRunner().canRun(executorId, environment.getRunProfile())) { return false; } else { @@ -198,23 +198,27 @@ extends BeforeRunTaskProvider<RunConfigurationBeforeRunProvider.RunConfigurableB final Disposable disposable = Disposer.newDisposable(); myProject.getMessageBus().connect(disposable).subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionAdapter() { + @Override public void processStartScheduled(final String executorIdLocal, final ExecutionEnvironment environmentLocal) { if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) { targetDone.down(); } } + @Override public void processNotStarted(final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal) { if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) { targetDone.up(); } } + @Override public void processStarted(final String executorIdLocal, @NotNull final ExecutionEnvironment environmentLocal, @NotNull final ProcessHandler handler) { if (executorId.equals(executorIdLocal) && environment.equals(environmentLocal)) { handler.addProcessListener(new ProcessAdapter() { + @Override public void processTerminated(ProcessEvent event) { result.set(event.getExitCode() == 0); targetDone.up(); @@ -229,7 +233,7 @@ extends BeforeRunTaskProvider<RunConfigurationBeforeRunProvider.RunConfigurableB @Override public void run() { try { - runner.execute(environment); + environment.getRunner().execute(environment); } catch (ExecutionException e) { targetDone.up(); diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunDialog.java b/platform/lang-impl/src/com/intellij/execution/impl/RunDialog.java index 71e205c3f22c..139eb0c4e25b 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunDialog.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunDialog.java @@ -20,6 +20,7 @@ import com.intellij.execution.ExecutionBundle; import com.intellij.execution.Executor; import com.intellij.execution.RunnerAndConfigurationSettings; import com.intellij.execution.configurations.RunConfiguration; +import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.ex.SingleConfigurableEditor; @@ -111,6 +112,10 @@ public class RunDialog extends DialogWrapper implements RunConfigurable.RunDialo return editConfiguration(project, configuration, title, null); } + public static boolean editConfiguration(@NotNull ExecutionEnvironment environment, @NotNull String title) { + return editConfiguration(environment.getProject(), environment.getRunnerAndConfigurationSettings(), title, environment.getExecutor()); + } + public static boolean editConfiguration(final Project project, final RunnerAndConfigurationSettings configuration, final String title, @Nullable final Executor executor) { final SingleConfigurationConfigurable<RunConfiguration> configurable = SingleConfigurationConfigurable.editSettings(configuration, executor); final SingleConfigurableEditor dialog = new SingleConfigurableEditor(project, configurable, IdeModalityType.PROJECT) { diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java index d3a1e1cb0574..7b54f21503df 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java @@ -19,6 +19,7 @@ package com.intellij.execution.impl; import com.intellij.ProjectTopics; import com.intellij.execution.*; import com.intellij.execution.configurations.*; +import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.Disposable; import com.intellij.openapi.components.NamedComponent; @@ -106,7 +107,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, public final void initializeConfigurationTypes(@NotNull final ConfigurationType[] factories) { Arrays.sort(factories, new Comparator<ConfigurationType>() { @Override - public int compare(final ConfigurationType o1, final ConfigurationType o2) { + public int compare(@NotNull final ConfigurationType o1, @NotNull final ConfigurationType o2) { return o1.getDisplayName().compareTo(o2.getDisplayName()); } }); @@ -461,7 +462,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, // IDEA-63663 Sort run configurations alphabetically if clean checkout Collections.sort(order, new Comparator<Pair<String, RunnerAndConfigurationSettings>>() { @Override - public int compare(Pair<String, RunnerAndConfigurationSettings> o1, Pair<String, RunnerAndConfigurationSettings> o2) { + public int compare(@NotNull Pair<String, RunnerAndConfigurationSettings> o1, @NotNull Pair<String, RunnerAndConfigurationSettings> o2) { boolean temporary1 = o1.getSecond().isTemporary(); boolean temporary2 = o2.getSecond().isTemporary(); if (temporary1 == temporary2) { @@ -475,7 +476,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, else { Collections.sort(order, new Comparator<Pair<String, RunnerAndConfigurationSettings>>() { @Override - public int compare(Pair<String, RunnerAndConfigurationSettings> o1, Pair<String, RunnerAndConfigurationSettings> o2) { + public int compare(@NotNull Pair<String, RunnerAndConfigurationSettings> o1, @NotNull Pair<String, RunnerAndConfigurationSettings> o2) { int i1 = folderNames.indexOf(o1.getSecond().getFolderName()); int i2 = folderNames.indexOf(o2.getSecond().getFolderName()); if (i1 != i2) { @@ -507,8 +508,12 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, return myConfigurations.values(); } - public static boolean canRunConfiguration(@NotNull final RunnerAndConfigurationSettings configuration, - @NotNull final Executor executor) { + public static boolean canRunConfiguration(@NotNull ExecutionEnvironment environment) { + RunnerAndConfigurationSettings runnerAndConfigurationSettings = environment.getRunnerAndConfigurationSettings(); + return runnerAndConfigurationSettings != null && canRunConfiguration(runnerAndConfigurationSettings, environment.getExecutor()); + } + + public static boolean canRunConfiguration(@NotNull RunnerAndConfigurationSettings configuration, @NotNull Executor executor) { try { configuration.checkSettings(executor); } @@ -567,7 +572,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, if (myUnknownElements != null) { for (Element unloadedElement : myUnknownElements) { - parentNode.addContent((Element)unloadedElement.clone()); + parentNode.addContent(unloadedElement.clone()); } } } @@ -647,7 +652,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, final Comparator<Element> comparator = new Comparator<Element>() { @Override - public int compare(Element a, Element b) { + public int compare(@NotNull Element a, @NotNull Element b) { final boolean aDefault = Boolean.valueOf(a.getAttributeValue("default", "false")); final boolean bDefault = Boolean.valueOf(b.getAttributeValue("default", "false")); return aDefault == bDefault ? 0 : aDefault ? -1 : 1; @@ -666,7 +671,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, Collections.sort(sortedElements, comparator); // ensure templates are loaded first! for (final Element element : sortedElements) { - RunnerAndConfigurationSettings configurationSettings = null; + RunnerAndConfigurationSettings configurationSettings; try { configurationSettings = loadConfiguration(element, false); } @@ -915,6 +920,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, public List<RunnerAndConfigurationSettings> getTempConfigurationsList() { List<RunnerAndConfigurationSettings> configurations = ContainerUtil.filter(myConfigurations.values(), new Condition<RunnerAndConfigurationSettings>() { + @Override public boolean value(RunnerAndConfigurationSettings settings) { return settings.isTemporary(); } @@ -933,6 +939,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, return result; } + @Override public void makeStable(@NotNull RunnerAndConfigurationSettings settings) { settings.setTemporary(false); myRecentlyUsedTemporaries.remove(settings.getConfiguration()); diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunnerRegistryImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/RunnerRegistryImpl.java index 08e9541c265f..cefeaf958f0d 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunnerRegistryImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunnerRegistryImpl.java @@ -51,10 +51,12 @@ public class RunnerRegistryImpl extends RunnerRegistry { } @Override - public ProgramRunner getRunner(@NotNull final String executorId, final RunProfile settings) { - if (settings == null) return null; - final ProgramRunner[] runners = getRegisteredRunners(); - for (final ProgramRunner runner : runners) { + public ProgramRunner getRunner(@NotNull String executorId, @Nullable RunProfile settings) { + if (settings == null) { + return null; + } + + for (ProgramRunner runner : getRegisteredRunners()) { if (runner.canRun(executorId, settings)) { return runner; } diff --git a/platform/lang-impl/src/com/intellij/execution/impl/SingleConfigurationConfigurable.java b/platform/lang-impl/src/com/intellij/execution/impl/SingleConfigurationConfigurable.java index 4c58ab7029b3..4a750f22a15d 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/SingleConfigurationConfigurable.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/SingleConfigurationConfigurable.java @@ -151,12 +151,10 @@ public final class SingleConfigurationConfigurable<Config extends RunConfigurati if (snapshot != null) { snapshot.setName(getNameText()); snapshot.checkSettings(myExecutor); - for (ProgramRunner runner : RunnerRegistry.getInstance().getRegisteredRunners()) { - for (Executor executor : ExecutorRegistry.getInstance().getRegisteredExecutors()) { - if (runner.canRun(executor.getId(), snapshot.getConfiguration())) { - checkConfiguration(runner, snapshot); - break; - } + for (Executor executor : ExecutorRegistry.getInstance().getRegisteredExecutors()) { + ProgramRunner runner = RunnerRegistry.getInstance().getRunner(executor.getId(), snapshot.getConfiguration()); + if (runner != null) { + checkConfiguration(runner, snapshot); } } } diff --git a/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java b/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java index b4b3cd919ec4..7bcabebf256a 100644 --- a/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java +++ b/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java @@ -173,7 +173,7 @@ public abstract class AbstractConsoleRunnerWithHistory<T extends LanguageConsole return false; } - protected void showConsole(Executor defaultExecutor, RunContentDescriptor contentDescriptor) { + protected void showConsole(Executor defaultExecutor, @NotNull RunContentDescriptor contentDescriptor) { // Show in run toolwindow ExecutionManager.getInstance(myProject).getContentManager().showRunContent(defaultExecutor, contentDescriptor); } diff --git a/platform/lang-impl/src/com/intellij/execution/runners/DefaultProgramRunner.java b/platform/lang-impl/src/com/intellij/execution/runners/DefaultProgramRunner.java index e2f8a5a717fe..5f7321aa8068 100644 --- a/platform/lang-impl/src/com/intellij/execution/runners/DefaultProgramRunner.java +++ b/platform/lang-impl/src/com/intellij/execution/runners/DefaultProgramRunner.java @@ -36,10 +36,10 @@ public abstract class DefaultProgramRunner extends GenericProgramRunner { @NotNull final ExecutionEnvironment env) throws ExecutionException { FileDocumentManager.getInstance().saveAllDocuments(); ExecutionResult executionResult = state.execute(env.getExecutor(), this); - if (executionResult == null) return null; - - final RunContentBuilder contentBuilder = new RunContentBuilder(this, executionResult, env); - return contentBuilder.showRunContent(contentToReuse); + if (executionResult == null) { + return null; + } + return new RunContentBuilder(executionResult, env).showRunContent(contentToReuse); } } diff --git a/platform/lang-impl/src/com/intellij/execution/runners/FakeRerunAction.java b/platform/lang-impl/src/com/intellij/execution/runners/FakeRerunAction.java index 45393c328e69..ecc8fa553121 100644 --- a/platform/lang-impl/src/com/intellij/execution/runners/FakeRerunAction.java +++ b/platform/lang-impl/src/com/intellij/execution/runners/FakeRerunAction.java @@ -15,33 +15,127 @@ */ package com.intellij.execution.runners; +import com.intellij.execution.ExecutionBundle; +import com.intellij.execution.ExecutorRegistry; +import com.intellij.execution.impl.ExecutionManagerImpl; +import com.intellij.execution.process.ProcessHandler; +import com.intellij.execution.ui.RunContentDescriptor; +import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.project.DumbAware; import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.List; /** * @author Roman.Chernyatchik */ -public class FakeRerunAction extends AnAction implements DumbAware { - protected static final List<RestartAction> registry = ContainerUtil.createLockFreeCopyOnWriteList(); +class FakeRerunAction extends AnAction implements DumbAware { + @SuppressWarnings("deprecation") + static final List<RestartAction> registry = ContainerUtil.createLockFreeCopyOnWriteList(); @Override - public void actionPerformed(AnActionEvent e) { - RestartAction action = RestartAction.findActualAction(); - if (action != null && action.isEnabled()) { - action.actionPerformed(e); + public void update(AnActionEvent event) { + Presentation presentation = event.getPresentation(); + ExecutionEnvironment environment = getEnvironment(event); + if (environment != null) { + presentation.setText(ExecutionBundle.message("rerun.configuration.action.name", environment.getRunProfile().getName())); + presentation.setIcon(ExecutionManagerImpl.isProcessRunning(getDescriptor(event)) ? AllIcons.Actions.Restart : environment.getExecutor().getIcon()); + presentation.setEnabledAndVisible(isEnabled(event)); + return; } + + FakeRerunAction action = findActualAction(event); + presentation.setEnabled(action != null && action.isEnabled(event)); + presentation.setVisible(false); } @Override - public void update(AnActionEvent e) { - final Presentation presentation = e.getPresentation(); - RestartAction action = RestartAction.findActualAction(); - presentation.setEnabled(action != null && action.isEnabled()); - presentation.setVisible(false); + public void actionPerformed(AnActionEvent event) { + ExecutionEnvironment environment = getEnvironment(event); + if (environment != null) { + ExecutionUtil.restart(environment); + return; + } + + FakeRerunAction action = findActualAction(event); + if (action != null && action.isEnabled(event)) { + action.actionPerformed(event); + } + } + + @Nullable + protected RunContentDescriptor getDescriptor(AnActionEvent event) { + return event.getData(LangDataKeys.RUN_CONTENT_DESCRIPTOR); + } + + @Nullable + protected ExecutionEnvironment getEnvironment(AnActionEvent event) { + return event.getData(LangDataKeys.EXECUTION_ENVIRONMENT); + } + + protected boolean isEnabled(AnActionEvent event) { + RunContentDescriptor descriptor = getDescriptor(event); + ProcessHandler processHandler = descriptor == null ? null : descriptor.getProcessHandler(); + ExecutionEnvironment environment = getEnvironment(event); + return environment != null && + !ExecutorRegistry.getInstance().isStarting(environment) && + !(processHandler != null && processHandler.isProcessTerminating()); + } + + @Nullable + private JComponent getRunComponent(@NotNull AnActionEvent event) { + RunContentDescriptor descriptor = getDescriptor(event); + return descriptor == null ? null : descriptor.getComponent(); + } + + @Nullable + private static FakeRerunAction findActualAction(@NotNull final AnActionEvent event) { + if (registry.isEmpty()) { + return null; + } + + List<FakeRerunAction> candidates = new ArrayList<FakeRerunAction>(registry); + Collections.sort(candidates, new Comparator<FakeRerunAction>() { + @Override + public int compare(@NotNull FakeRerunAction action1, @NotNull FakeRerunAction action2) { + boolean isActive1 = action1.isEnabled(event); + if (isActive1 != action2.isEnabled(event)) { + return isActive1 ? -1 : 1; + } + + JComponent component1 = action1.getRunComponent(event); + JComponent component2 = action2.getRunComponent(event); + Window window1 = component1 == null ? null : SwingUtilities.windowForComponent(component1); + Window window2 = component2 == null ? null : SwingUtilities.windowForComponent(component2); + if (window1 == null) { + return 1; + } + if (window2 == null) { + return -1; + } + + boolean showing1 = component1.isShowing(); + boolean showing2 = component2.isShowing(); + if (showing1 && !showing2) { + return -1; + } + if (showing2 && !showing1) { + return 1; + } + return (window1.isActive() ? -1 : 1); + } + }); + return candidates.get(0); } } diff --git a/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsAction.java b/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsAction.java index c4e8fd0a3e0d..8d3bf8663598 100644 --- a/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsAction.java +++ b/platform/lang-impl/src/com/intellij/execution/runners/RerunTestsAction.java @@ -1,13 +1,11 @@ package com.intellij.execution.runners; -import com.intellij.execution.ExecutionManager; -import com.intellij.execution.ExecutorRegistry; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.openapi.Disposable; -import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.DumbAwareAction; -import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; @@ -25,41 +23,27 @@ import java.util.List; * @author Sergey Simonchik */ public class RerunTestsAction extends DumbAwareAction implements AnAction.TransparentUpdate { - public static final String ID = "RerunTests"; - private static final List<RerunInfo> REGISTRY = ContainerUtil.createLockFreeCopyOnWriteList(); + private static final List<ExecutionEnvironment> REGISTRY = ContainerUtil.createLockFreeCopyOnWriteList(); - public static void register(@NotNull RunContentDescriptor descriptor, - @NotNull ExecutionEnvironment env, - @NotNull ProgramRunner runner) { - final RerunInfo rerunInfo = new RerunInfo(descriptor, env, runner); - REGISTRY.add(rerunInfo); - Disposer.register(descriptor, new Disposable() { + public static void register(@NotNull final ExecutionEnvironment environment) { + REGISTRY.add(environment); + Disposer.register(environment, new Disposable() { @Override public void dispose() { - REGISTRY.remove(rerunInfo); + REGISTRY.remove(environment); } }); } @Override public void actionPerformed(AnActionEvent e) { - DataContext dataContext = e.getDataContext(); - Project project = CommonDataKeys.PROJECT.getData(dataContext); - if (project == null) { - return; - } - ExecutionManager executionManager = ExecutionManager.getInstance(project); - for (RerunInfo rerunInfo : REGISTRY) { - RunContentDescriptor descriptor = rerunInfo.getDescriptor(); - if (!Disposer.isDisposed(descriptor)) { - ExecutionEnvironment env = rerunInfo.getEnv(); - ProgramRunner runner = rerunInfo.getRunner(); - ProcessHandler processHandler = descriptor.getProcessHandler(); + for (ExecutionEnvironment environment : REGISTRY) { + if (!Disposer.isDisposed(environment)) { + RunContentDescriptor descriptor = environment.getContentToReuse(); + ProcessHandler processHandler = descriptor == null ? null : descriptor.getProcessHandler(); if (processHandler != null && processHandler.isProcessTerminated()) { - if (!ExecutorRegistry.getInstance().isStarting(project, env.getExecutor().getId(), runner.getRunnerId())) { - executionManager.restartRunProfile(runner, env, descriptor); - } + ExecutionUtil.restart(environment); } } } @@ -67,35 +51,6 @@ public class RerunTestsAction extends DumbAwareAction implements AnAction.Transp @Override public void update(AnActionEvent e) { - Presentation presentation = e.getPresentation(); - presentation.setEnabled(true); - } - - private static class RerunInfo { - - private final RunContentDescriptor myDescriptor; - private final ExecutionEnvironment myEnv; - private final ProgramRunner myRunner; - - public RerunInfo(@NotNull RunContentDescriptor descriptor, - @NotNull ExecutionEnvironment env, - @NotNull ProgramRunner runner) { - myDescriptor = descriptor; - myEnv = env; - myRunner = runner; - } - - private RunContentDescriptor getDescriptor() { - return myDescriptor; - } - - private ExecutionEnvironment getEnv() { - return myEnv; - } - - private ProgramRunner getRunner() { - return myRunner; - } + e.getPresentation().setEnabled(true); } - } diff --git a/platform/lang-impl/src/com/intellij/execution/runners/RestartAction.java b/platform/lang-impl/src/com/intellij/execution/runners/RestartAction.java index 20b29c2de994..1ab3cee3c8cb 100644 --- a/platform/lang-impl/src/com/intellij/execution/runners/RestartAction.java +++ b/platform/lang-impl/src/com/intellij/execution/runners/RestartAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,129 +15,69 @@ */ package com.intellij.execution.runners; -import com.intellij.execution.ExecutionBundle; -import com.intellij.execution.ExecutionManager; import com.intellij.execution.Executor; -import com.intellij.execution.ExecutorRegistry; -import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.ui.RunContentDescriptor; -import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; -import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CustomShortcutSet; +import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.project.DumbAware; -import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; -import java.awt.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; +@Deprecated /** - * @author dyoma + * to remove in IDEA 15 */ public class RestartAction extends FakeRerunAction implements DumbAware, AnAction.TransparentUpdate, Disposable { - - private final ProgramRunner myRunner; - @NotNull private final RunContentDescriptor myDescriptor; - @NotNull private final Executor myExecutor; + private final RunContentDescriptor myDescriptor; private final ExecutionEnvironment myEnvironment; - public RestartAction(@NotNull final Executor executor, - final ProgramRunner runner, - @NotNull final RunContentDescriptor descriptor, - @NotNull final ExecutionEnvironment env) { + public RestartAction(@NotNull RunContentDescriptor descriptor, @NotNull ExecutionEnvironment environment) { + //noinspection deprecation + this(environment.getExecutor(), null, descriptor, environment); + } + + @Deprecated + /** + * @deprecated environment must provide runner id + * to remove in IDEA 15 + */ + public RestartAction(@SuppressWarnings("UnusedParameters") @NotNull Executor executor, + @Nullable ProgramRunner runner, + @NotNull RunContentDescriptor descriptor, + @NotNull ExecutionEnvironment environment) { Disposer.register(descriptor, this); - registry.add(this); + FakeRerunAction.registry.add(this); - myEnvironment = env; + myEnvironment = runner == null ? environment : RunContentBuilder.fix(environment, runner); getTemplatePresentation().setEnabled(false); - myRunner = runner; myDescriptor = descriptor; - myExecutor = executor; - // see IDEADEV-698 - - if (descriptor.getRestarter() == null) { - descriptor.setRestarter(new Runnable() { - @Override - public void run() { - restart(); - } - }); - } } @Override public void dispose() { - registry.remove(this); - } - - @Nullable - static RestartAction findActualAction() { - if (registry.isEmpty()) - return null; - List<RestartAction> candidates = new ArrayList<RestartAction>(registry); - Collections.sort(candidates, new Comparator<RestartAction>() { - @Override - public int compare(RestartAction action1, RestartAction action2) { - boolean isActive1 = action1.isEnabled(); - boolean isActive2 = action2.isEnabled(); - if (isActive1 != isActive2) - return isActive1? - 1 : 1; - Window window1 = SwingUtilities.windowForComponent(action1.myDescriptor.getComponent()); - Window window2 = SwingUtilities.windowForComponent(action2.myDescriptor.getComponent()); - if (window1 == null) - return 1; - if (window2 == null) - return -1; - boolean showing1 = action1.myDescriptor.getComponent().isShowing(); - boolean showing2 = action2.myDescriptor.getComponent().isShowing(); - if (showing1 && !showing2) - return -1; - if (showing2 && !showing1) - return 1; - return (window1.isActive() ? -1 : 1); - } - }); - return candidates.get(0); + FakeRerunAction.registry.remove(this); } @Override - public void actionPerformed(final AnActionEvent e) { - restart(); - } - - public void restart() { - Project project = myEnvironment.getProject(); - if (!ExecutorRegistry.getInstance().isStarting(project, myExecutor.getId(), myRunner.getRunnerId())) - ExecutionManager.getInstance(project).restartRunProfile(myRunner, myEnvironment, myDescriptor); + @NotNull + protected RunContentDescriptor getDescriptor(AnActionEvent event) { + return myDescriptor; } @Override - public void update(final AnActionEvent event) { - final Presentation presentation = event.getPresentation(); - String name = myEnvironment.getRunProfile().getName(); - ProcessHandler processHandler = myDescriptor.getProcessHandler(); - final boolean isRunning = processHandler != null && !processHandler.isProcessTerminated(); - - presentation.setText(ExecutionBundle.message("rerun.configuration.action.name", name)); - presentation.setIcon(isRunning ? AllIcons.Actions.Restart : myExecutor.getIcon()); - presentation.setEnabled(isEnabled()); - } - - boolean isEnabled() { - ProcessHandler processHandler = myDescriptor.getProcessHandler(); - boolean isTerminating = processHandler != null && processHandler.isProcessTerminating(); - boolean isStarting = ExecutorRegistry.getInstance().isStarting(myEnvironment.getProject(), myExecutor.getId(), myRunner.getRunnerId()); - return !isStarting && !isTerminating; + @NotNull + protected ExecutionEnvironment getEnvironment(AnActionEvent event) { + return myEnvironment; } - public void registerShortcut(final JComponent component) { + public void registerShortcut(JComponent component) { registerCustomShortcutSet(new CustomShortcutSet(KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_RERUN)), component); } diff --git a/platform/lang-impl/src/com/intellij/execution/runners/RunContentBuilder.java b/platform/lang-impl/src/com/intellij/execution/runners/RunContentBuilder.java index bb6d206f1eb9..f16f8dadfb45 100644 --- a/platform/lang-impl/src/com/intellij/execution/runners/RunContentBuilder.java +++ b/platform/lang-impl/src/com/intellij/execution/runners/RunContentBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,6 @@ */ package com.intellij.execution.runners; -import com.intellij.diagnostic.logging.LogConsoleManagerBase; -import com.intellij.diagnostic.logging.LogFilesManager; -import com.intellij.diagnostic.logging.OutputFileUtil; import com.intellij.execution.DefaultExecutionResult; import com.intellij.execution.ExecutionManager; import com.intellij.execution.ExecutionResult; @@ -32,7 +29,6 @@ import com.intellij.execution.ui.actions.CloseAction; import com.intellij.execution.ui.layout.PlaceInGrid; import com.intellij.icons.AllIcons; import com.intellij.ide.actions.ContextHelpAction; -import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; @@ -40,115 +36,91 @@ import com.intellij.openapi.util.Disposer; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.ui.content.Content; import com.intellij.ui.content.tabs.PinToolwindowTabAction; +import com.intellij.util.SmartList; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import javax.swing.*; -import java.util.ArrayList; import java.util.Collection; +import java.util.List; -/** - * @author dyoma - */ -public class RunContentBuilder extends LogConsoleManagerBase { +public class RunContentBuilder extends RunTab { @NonNls private static final String JAVA_RUNNER = "JavaRunner"; - private final ProgramRunner myRunner; - private final ArrayList<AnAction> myRunnerActions = new ArrayList<AnAction>(); - private ExecutionResult myExecutionResult; - - private final LogFilesManager myManager; - - private RunnerLayoutUi myUi; - private final Executor myExecutor; + private final List<AnAction> myRunnerActions = new SmartList<AnAction>(); + private final ExecutionResult myExecutionResult; /** - * @deprecated use {@link #RunContentBuilder(ProgramRunner, com.intellij.execution.ExecutionResult, ExecutionEnvironment)} + * @deprecated use {@link #RunContentBuilder(com.intellij.execution.ExecutionResult, ExecutionEnvironment)} + * to remove in IDEA 14 */ + @SuppressWarnings("UnusedParameters") public RunContentBuilder(@NotNull Project project, ProgramRunner runner, Executor executor, ExecutionResult executionResult, @NotNull ExecutionEnvironment environment) { + //noinspection deprecation this(runner, executionResult, environment); } + /** + * @deprecated use {@link #RunContentBuilder(com.intellij.execution.ExecutionResult, ExecutionEnvironment)} + * to remove in IDEA 15 + */ public RunContentBuilder(ProgramRunner runner, ExecutionResult executionResult, @NotNull ExecutionEnvironment environment) { - super(environment.getProject(), SearchScopeProvider.createSearchScope(environment.getProject(), environment.getRunProfile())); - myRunner = runner; - myExecutor = environment.getExecutor(); - myManager = new LogFilesManager(environment.getProject(), this, this); + this(executionResult, fix(environment, runner)); + } + + public RunContentBuilder(@NotNull ExecutionResult executionResult, @NotNull ExecutionEnvironment environment) { + super(environment, getRunnerType(executionResult.getExecutionConsole())); + myExecutionResult = executionResult; - setEnvironment(environment); + myUi.getOptions().setMoveToGridActionEnabled(false).setMinimizeActionEnabled(false); } - /** - * @deprecated use {@link #RunContentBuilder(com.intellij.openapi.project.Project, ProgramRunner, com.intellij.execution.Executor, com.intellij.execution.ExecutionResult, ExecutionEnvironment)} - */ - public RunContentBuilder(final Project project, final ProgramRunner runner, Executor executor) { - super(project); - myRunner = runner; - myExecutor = executor; - myManager = new LogFilesManager(project, this, this); + @NotNull + public static ExecutionEnvironment fix(@NotNull ExecutionEnvironment environment, @Nullable ProgramRunner runner) { + if (runner == null || runner.equals(environment.getRunner())) { + return environment; + } + else { + return new ExecutionEnvironmentBuilder(environment).runner(runner).build(); + } } + @SuppressWarnings("UnusedDeclaration") @Deprecated @NotNull + /** + * @deprecated to remove in IDEA 15 + */ public static GlobalSearchScope createSearchScope(Project project, RunProfile runProfile) { return SearchScopeProvider.createSearchScope(project, runProfile); } + @NotNull public ExecutionResult getExecutionResult() { return myExecutionResult; } - @Deprecated - public void setExecutionResult(final ExecutionResult executionResult) { - myExecutionResult = executionResult; - } - - @Override - public void setEnvironment(@NotNull final ExecutionEnvironment env) { - super.setEnvironment(env); - final RunProfile profile = env.getRunProfile(); - if (profile instanceof RunConfigurationBase) { - myManager.registerFileMatcher((RunConfigurationBase)profile); - } - } - public void addAction(@NotNull final AnAction action) { myRunnerActions.add(action); } + @NotNull private RunContentDescriptor createDescriptor() { - if (myExecutionResult == null) { - throw new IllegalStateException("Missing ExecutionResult"); - } - - ExecutionEnvironment environment = getEnvironment(); - if (environment == null) { - throw new IllegalStateException("Missing ExecutionEnvironment"); - } - - final RunProfile profile = environment.getRunProfile(); - - final ExecutionConsole console = myExecutionResult.getExecutionConsole(); - String runnerType = JAVA_RUNNER; - if (console instanceof ExecutionConsoleEx) { - final String id = ((ExecutionConsoleEx)console).getExecutionConsoleId(); - if (id != null) { - runnerType = JAVA_RUNNER + "." + id; - } - } - myUi = RunnerLayoutUi.Factory.getInstance(getProject()).create(runnerType, myExecutor.getId(), profile.getName(), this); - myUi.getOptions().setMoveToGridActionEnabled(false).setMinimizeActionEnabled(false); - + final RunProfile profile = getEnvironment().getRunProfile(); if (ApplicationManager.getApplication().isUnitTestMode()) { - return new MyRunContentDescriptor(profile, myExecutionResult, myUi.getComponent(), this); + RunContentDescriptor contentDescriptor = new RunContentDescriptor(profile, myExecutionResult, myUi); + Disposer.register(contentDescriptor, this); + return contentDescriptor; } + final ExecutionConsole console = myExecutionResult.getExecutionConsole(); if (console != null) { if (console instanceof ExecutionConsoleEx) { ((ExecutionConsoleEx)console).buildUi(myUi); @@ -156,19 +128,17 @@ public class RunContentBuilder extends LogConsoleManagerBase { else { buildConsoleUiDefault(myUi, console); } - if (profile instanceof RunConfigurationBase) { - myManager.initLogConsoles((RunConfigurationBase)profile, myExecutionResult.getProcessHandler()); - OutputFileUtil.attachDumpListener((RunConfigurationBase)profile, myExecutionResult.getProcessHandler(), console); - } + initLogConsoles(profile, myExecutionResult.getProcessHandler(), console); } - MyRunContentDescriptor contentDescriptor = new MyRunContentDescriptor(profile, myExecutionResult, myUi.getComponent(), this); - myUi.getOptions().setLeftToolbar(createActionToolbar(contentDescriptor, myUi.getComponent()), ActionPlaces.UNKNOWN); + RunContentDescriptor contentDescriptor = new RunContentDescriptor(profile, myExecutionResult, myUi); + Disposer.register(contentDescriptor, this); + myUi.getOptions().setLeftToolbar(createActionToolbar(contentDescriptor), ActionPlaces.UNKNOWN); if (profile instanceof RunConfigurationBase) { if (console instanceof ObservableConsoleView && !ApplicationManager.getApplication().isUnitTestMode()) { ((ObservableConsoleView)console).addChangeListener(new ConsoleToFrontListener((RunConfigurationBase)profile, getProject(), - myExecutor, + getEnvironment().getExecutor(), contentDescriptor, myUi), this); @@ -178,10 +148,22 @@ public class RunContentBuilder extends LogConsoleManagerBase { return contentDescriptor; } + @NotNull + private static String getRunnerType(@Nullable ExecutionConsole console) { + String runnerType = JAVA_RUNNER; + if (console instanceof ExecutionConsoleEx) { + String id = ((ExecutionConsoleEx)console).getExecutionConsoleId(); + if (id != null) { + return JAVA_RUNNER + '.' + id; + } + } + return runnerType; + } + public static void buildConsoleUiDefault(RunnerLayoutUi ui, final ExecutionConsole console) { final Content consoleContent = ui.createContent(ExecutionConsole.CONSOLE_CONTENT_ID, console.getComponent(), "Console", AllIcons.Debugger.Console, - console.getPreferredFocusableComponent()); + console.getPreferredFocusableComponent()); consoleContent.setCloseable(false); addAdditionalConsoleEditorActions(console, consoleContent); @@ -191,22 +173,18 @@ public class RunContentBuilder extends LogConsoleManagerBase { public static void addAdditionalConsoleEditorActions(final ExecutionConsole console, final Content consoleContent) { final DefaultActionGroup consoleActions = new DefaultActionGroup(); if (console instanceof ConsoleView) { - AnAction[] actions = ((ConsoleView)console).createConsoleActions(); - for (AnAction goaction: actions) { - consoleActions.add(goaction); + for (AnAction action : ((ConsoleView)console).createConsoleActions()) { + consoleActions.add(action); } } consoleContent.setActions(consoleActions, ActionPlaces.UNKNOWN, console.getComponent()); } - private ActionGroup createActionToolbar(final RunContentDescriptor contentDescriptor, final JComponent component) { + @NotNull + private ActionGroup createActionToolbar(@NotNull RunContentDescriptor contentDescriptor) { final DefaultActionGroup actionGroup = new DefaultActionGroup(); - - final RestartAction restartAction = new RestartAction(myExecutor, myRunner, contentDescriptor, getEnvironment()); - restartAction.registerShortcut(component); - actionGroup.add(restartAction); - + actionGroup.add(ActionManager.getInstance().getAction(IdeActions.ACTION_RERUN)); if (myExecutionResult instanceof DefaultExecutionResult) { final AnAction[] actions = ((DefaultExecutionResult)myExecutionResult).getRestartActions(); if (actions != null) { @@ -217,15 +195,14 @@ public class RunContentBuilder extends LogConsoleManagerBase { } } - final AnAction stopAction = ActionManager.getInstance().getAction(IdeActions.ACTION_STOP_PROGRAM); - actionGroup.add(stopAction); + actionGroup.add(ActionManager.getInstance().getAction(IdeActions.ACTION_STOP_PROGRAM)); if (myExecutionResult instanceof DefaultExecutionResult) { actionGroup.addAll(((DefaultExecutionResult)myExecutionResult).getAdditionalStopActions()); } actionGroup.addAll(myExecutionResult.getActions()); - for (final AnAction anAction : myRunnerActions) { + for (AnAction anAction : myRunnerActions) { if (anAction != null) { actionGroup.add(anAction); } @@ -238,9 +215,9 @@ public class RunContentBuilder extends LogConsoleManagerBase { actionGroup.add(myUi.getOptions().getLayoutActions()); actionGroup.addSeparator(); actionGroup.add(PinToolwindowTabAction.getPinAction()); - actionGroup.add(new CloseAction(myExecutor, contentDescriptor, getProject())); + actionGroup.add(new CloseAction(getEnvironment().getExecutor(), contentDescriptor, getProject())); final String helpId = contentDescriptor.getHelpId(); - actionGroup.add(new ContextHelpAction(helpId != null ? helpId : myExecutor.getHelpId())); + actionGroup.add(new ContextHelpAction(helpId != null ? helpId : getEnvironment().getExecutor().getHelpId())); return actionGroup; } @@ -252,14 +229,10 @@ public class RunContentBuilder extends LogConsoleManagerBase { /** * @param reuseContent see {@link RunContentDescriptor#myContent} */ - public RunContentDescriptor showRunContent(final RunContentDescriptor reuseContent) { - final RunContentDescriptor descriptor = createDescriptor(); - if (reuseContent != null) { - descriptor.setAttachedContent(reuseContent.getAttachedContent()); - if (reuseContent.isReuseToolWindowActivation()) { - descriptor.setActivateToolWindowWhenAdded(reuseContent.isActivateToolWindowWhenAdded()); - } - } + public RunContentDescriptor showRunContent(@Nullable RunContentDescriptor reuseContent) { + RunContentDescriptor descriptor = createDescriptor(); + RunContentManagerImpl.copyContentAndBehavior(descriptor, reuseContent); + myRunContentDescriptor = descriptor; return descriptor; } @@ -273,21 +246,6 @@ public class RunContentBuilder extends LogConsoleManagerBase { return AllIcons.Debugger.Console; } - private static class MyRunContentDescriptor extends RunContentDescriptor { - private final Disposable myAdditionalDisposable; - - public MyRunContentDescriptor(final RunProfile profile, final ExecutionResult executionResult, final JComponent component, @NotNull Disposable additionalDisposable) { - super(executionResult.getExecutionConsole(), executionResult.getProcessHandler(), component, profile.getName(), profile.getIcon()); - myAdditionalDisposable = additionalDisposable; - } - - @Override - public void dispose() { - Disposer.dispose(myAdditionalDisposable); - super.dispose(); - } - } - public static class ConsoleToFrontListener implements ConsoleViewImpl.ChangeListener { @NotNull private final RunConfigurationBase myRunConfigurationBase; @NotNull private final Project myProject; diff --git a/platform/lang-impl/src/com/intellij/execution/runners/RunTab.java b/platform/lang-impl/src/com/intellij/execution/runners/RunTab.java new file mode 100644 index 000000000000..2edc2098ce15 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/execution/runners/RunTab.java @@ -0,0 +1,94 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.execution.runners; + +import com.intellij.diagnostic.logging.LogConsoleManagerBase; +import com.intellij.diagnostic.logging.LogFilesManager; +import com.intellij.diagnostic.logging.OutputFileUtil; +import com.intellij.execution.configurations.RunConfigurationBase; +import com.intellij.execution.configurations.RunProfile; +import com.intellij.execution.configurations.SearchScopeProvider; +import com.intellij.execution.process.ProcessHandler; +import com.intellij.execution.ui.ExecutionConsole; +import com.intellij.execution.ui.RunContentDescriptor; +import com.intellij.execution.ui.RunnerLayoutUi; +import com.intellij.openapi.actionSystem.DataProvider; +import com.intellij.openapi.actionSystem.LangDataKeys; +import com.intellij.openapi.project.Project; +import com.intellij.psi.search.GlobalSearchScope; +import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public abstract class RunTab extends LogConsoleManagerBase implements DataProvider { + @NotNull + protected final RunnerLayoutUi myUi; + protected final LogFilesManager myManager; + protected RunContentDescriptor myRunContentDescriptor; + + protected RunTab(@NotNull ExecutionEnvironment environment, @NotNull String runnerType) { + this(environment.getProject(), + SearchScopeProvider.createSearchScope(environment.getProject(), environment.getRunProfile()), + runnerType, + environment.getExecutor().getId(), + environment.getRunProfile().getName()); + + setEnvironment(environment); + } + + protected RunTab(@NotNull Project project, @NotNull GlobalSearchScope searchScope, @NotNull String runnerType, @NotNull String runnerTitle, @NotNull String sessionName) { + super(project, searchScope); + + myManager = new LogFilesManager(project, this, this); + + myUi = RunnerLayoutUi.Factory.getInstance(getProject()).create(runnerType, runnerTitle, sessionName, this); + myUi.getContentManager().addDataProvider(this); + } + + @Nullable + @Override + public Object getData(@NonNls String dataId) { + if (LangDataKeys.RUN_PROFILE.is(dataId)) { + ExecutionEnvironment environment = getEnvironment(); + return environment == null ? null : environment.getRunProfile(); + } + else if (LangDataKeys.EXECUTION_ENVIRONMENT.is(dataId)) { + return getEnvironment(); + } + else if (LangDataKeys.RUN_CONTENT_DESCRIPTOR.is(dataId)) { + return myRunContentDescriptor; + } + return null; + } + + @Override + public final void setEnvironment(@NotNull ExecutionEnvironment environment) { + super.setEnvironment(environment); + + RunProfile profile = environment.getRunProfile(); + if (profile instanceof RunConfigurationBase) { + myManager.registerFileMatcher((RunConfigurationBase)profile); + } + } + + protected final void initLogConsoles(@NotNull RunProfile runConfiguration, @Nullable ProcessHandler processHandler, @Nullable ExecutionConsole console) { + if (runConfiguration instanceof RunConfigurationBase && processHandler != null) { + RunConfigurationBase configuration = (RunConfigurationBase)runConfiguration; + myManager.initLogConsoles(configuration, processHandler); + OutputFileUtil.attachDumpListener(configuration, processHandler, console); + } + } +} diff --git a/platform/lang-impl/src/com/intellij/execution/ui/RunContentManagerImpl.java b/platform/lang-impl/src/com/intellij/execution/ui/RunContentManagerImpl.java index 73ec463954cd..c9dae095522c 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/RunContentManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/RunContentManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,12 +46,14 @@ import com.intellij.openapi.wm.ToolWindowAnchor; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.ex.ToolWindowManagerAdapter; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; +import com.intellij.ui.AppUIUtil; import com.intellij.ui.content.*; import com.intellij.ui.docking.DockManager; +import com.intellij.util.SmartList; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.containers.HashMap; -import com.intellij.util.messages.Topic; +import gnu.trove.THashMap; +import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -59,60 +61,59 @@ import javax.swing.*; import java.util.*; public class RunContentManagerImpl implements RunContentManager, Disposable { - public static final Topic<RunContentWithExecutorListener> RUN_CONTENT_TOPIC = - Topic.create("Run Content", RunContentWithExecutorListener.class); public static final Key<Boolean> ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY = Key.create("ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY"); - private static final Logger LOG = Logger.getInstance("#com.intellij.execution.ui.RunContentManagerImpl"); - private static final Key<RunContentDescriptor> DESCRIPTOR_KEY = new Key<RunContentDescriptor>("Descriptor"); + private static final Logger LOG = Logger.getInstance(RunContentManagerImpl.class); + private static final Key<RunContentDescriptor> DESCRIPTOR_KEY = Key.create("Descriptor"); private final Project myProject; - private DockableGridContainerFactory myContentFactory; - private final Map<String, ContentManager> myToolwindowIdToContentManagerMap = new HashMap<String, ContentManager>(); + private final Map<String, ContentManager> myToolwindowIdToContentManagerMap = new THashMap<String, ContentManager>(); - private final Map<RunContentListener, Disposable> myListeners = new HashMap<RunContentListener, Disposable>(); - private final LinkedList<String> myToolwindowIdZbuffer = new LinkedList<String>(); + private final Map<RunContentListener, Disposable> myListeners = new THashMap<RunContentListener, Disposable>(); + private final LinkedList<String> myToolwindowIdZBuffer = new LinkedList<String>(); - public RunContentManagerImpl(Project project, DockManager dockManager) { + public RunContentManagerImpl(@NotNull Project project, @NotNull DockManager dockManager) { myProject = project; - myContentFactory = new DockableGridContainerFactory(); - dockManager.register(DockableGridContainerFactory.TYPE, myContentFactory); - Disposer.register(myProject, myContentFactory); + DockableGridContainerFactory containerFactory = new DockableGridContainerFactory(); + dockManager.register(DockableGridContainerFactory.TYPE, containerFactory); + Disposer.register(myProject, containerFactory); + + AppUIUtil.invokeOnEdt(new Runnable() { + @Override + public void run() { + init(); + } + }, myProject.getDisposed()); } - public void init() { - final Executor[] executors = ExecutorRegistry.getInstance().getRegisteredExecutors(); - for (Executor executor : executors) { - registerToolwindow(executor); + // must be called on EDT + private void init() { + ToolWindowManagerEx toolWindowManager = ToolWindowManagerEx.getInstanceEx(myProject); + if (toolWindowManager == null) { + return; } - if (ToolWindowManager.getInstance(myProject) == null) return; + for (Executor executor : ExecutorRegistry.getInstance().getRegisteredExecutors()) { + registerToolwindow(executor, toolWindowManager); + } - // To ensure ToolwindowManager had already initialized in its projectOpened. - SwingUtilities.invokeLater(new Runnable() { + toolWindowManager.addToolWindowManagerListener(new ToolWindowManagerAdapter() { @Override - public void run() { - if (myProject.isDisposed()) return; - ((ToolWindowManagerEx)ToolWindowManager.getInstance(myProject)).addToolWindowManagerListener(new ToolWindowManagerAdapter() { - @Override - public void stateChanged() { - if (myProject.isDisposed()) return; - - ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject); - - Set<String> currentWindows = new HashSet<String>(); - String[] toolWindowIds = toolWindowManager.getToolWindowIds(); + public void stateChanged() { + if (myProject.isDisposed()) { + return; + } - ContainerUtil.addAll(currentWindows, toolWindowIds); - myToolwindowIdZbuffer.retainAll(currentWindows); + ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject); + Set<String> currentWindows = new THashSet<String>(); + ContainerUtil.addAll(currentWindows, toolWindowManager.getToolWindowIds()); + myToolwindowIdZBuffer.retainAll(currentWindows); - final String activeToolWindowId = toolWindowManager.getActiveToolWindowId(); - if (activeToolWindowId != null) { - if (myToolwindowIdZbuffer.remove(activeToolWindowId)) { - myToolwindowIdZbuffer.addFirst(activeToolWindowId); - } - } + final String activeToolWindowId = toolWindowManager.getActiveToolWindowId(); + if (activeToolWindowId != null) { + if (myToolwindowIdZBuffer.remove(activeToolWindowId)) { + myToolwindowIdZBuffer.addFirst(activeToolWindowId); } - }); + } } }); } @@ -121,25 +122,15 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { public void dispose() { } - private void unregisterToolwindow(final String id) { - final ContentManager manager = myToolwindowIdToContentManagerMap.get(id); - manager.removeAllContents(true); - myToolwindowIdToContentManagerMap.remove(id); - myToolwindowIdZbuffer.remove(id); - } - - private void registerToolwindow(@NotNull final Executor executor) { + private void registerToolwindow(@NotNull final Executor executor, @NotNull ToolWindowManagerEx toolWindowManager) { final String toolWindowId = executor.getToolWindowId(); - final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(myProject); - if (toolWindowManager == null) return; //headless environment if (toolWindowManager.getToolWindow(toolWindowId) != null) { return; } - final ToolWindow toolWindow = toolWindowManager.registerToolWindow(toolWindowId, true, ToolWindowAnchor.BOTTOM, this, true); - + ToolWindow toolWindow = toolWindowManager.registerToolWindow(toolWindowId, true, ToolWindowAnchor.BOTTOM, this, true); final ContentManager contentManager = toolWindow.getContentManager(); - class MyDataProvider implements DataProvider { + contentManager.addDataProvider(new DataProvider() { private int myInsideGetData = 0; @Override @@ -157,31 +148,30 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { myInsideGetData--; } } - } - contentManager.addDataProvider(new MyDataProvider()); + }); toolWindow.setIcon(executor.getToolWindowIcon()); new ContentManagerWatcher(toolWindow, contentManager); contentManager.addContentManagerListener(new ContentManagerAdapter() { @Override public void selectionChanged(final ContentManagerEvent event) { - final Content content = event.getContent(); - final RunContentDescriptor descriptor = content != null ? getRunContentDescriptorByContent(content) : null; - getSyncPublisher().contentSelected(descriptor, executor); + Content content = event.getContent(); + getSyncPublisher().contentSelected(content == null ? null : getRunContentDescriptorByContent(content), executor); } }); myToolwindowIdToContentManagerMap.put(toolWindowId, contentManager); Disposer.register(contentManager, new Disposable() { @Override public void dispose() { - unregisterToolwindow(toolWindowId); + myToolwindowIdToContentManagerMap.remove(toolWindowId).removeAllContents(true); + myToolwindowIdZBuffer.remove(toolWindowId); } }); - myToolwindowIdZbuffer.addLast(toolWindowId); + myToolwindowIdZBuffer.addLast(toolWindowId); } private RunContentWithExecutorListener getSyncPublisher() { - return myProject.getMessageBus().syncPublisher(RUN_CONTENT_TOPIC); + return myProject.getMessageBus().syncPublisher(TOPIC); } @Override @@ -193,24 +183,19 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { toFrontRunContent(requestor, descriptor); } - @Override public void toFrontRunContent(final Executor requestor, final RunContentDescriptor descriptor) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { - final ContentManager contentManager = getContentManagerForRunner(requestor); - - final Content content = getRunContentByDescriptor(contentManager, descriptor); - - if (contentManager != null && content != null) { + ContentManager contentManager = getContentManagerForRunner(requestor); + Content content = getRunContentByDescriptor(contentManager, descriptor); + if (content != null) { contentManager.setSelectedContent(content); - - final ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(requestor.getToolWindowId()); - toolWindow.show(null); + ToolWindowManager.getInstance(myProject).getToolWindow(requestor.getToolWindowId()).show(null); } } - }); + }, myProject.getDisposed()); } @Override @@ -218,37 +203,25 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { - if (!myProject.isDisposed()) { - final String toolWindowId = executor.getToolWindowId(); - final ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(toolWindowId); - if (toolWindow != null) { - toolWindow.hide(null); - } + ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(executor.getToolWindowId()); + if (toolWindow != null) { + toolWindow.hide(null); } } - }); + }, myProject.getDisposed()); } @Override @Nullable public RunContentDescriptor getSelectedContent(final Executor executor) { - final ContentManager contentManager = getContentManagerForRunner(executor); - if (contentManager != null) { - final Content selectedContent = contentManager.getSelectedContent(); - if (selectedContent != null) { - final RunContentDescriptor runContentDescriptorByContent = getRunContentDescriptorByContent(selectedContent); - if (runContentDescriptorByContent != null) { - return runContentDescriptorByContent; - } - } - } - return null; + final Content selectedContent = getContentManagerForRunner(executor).getSelectedContent(); + return selectedContent != null ? getRunContentDescriptorByContent(selectedContent) : null; } @Override @Nullable public RunContentDescriptor getSelectedContent() { - for (String activeWindow : myToolwindowIdZbuffer) { + for (String activeWindow : myToolwindowIdZBuffer) { final ContentManager contentManager = myToolwindowIdToContentManagerMap.get(activeWindow); if (contentManager == null) { continue; @@ -280,32 +253,30 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { } @Override - public void showRunContent(@NotNull final Executor executor, final RunContentDescriptor descriptor) { - showRunContent(executor, descriptor, descriptor != null ? descriptor.getExecutionId() : 0L); + public void showRunContent(@NotNull Executor executor, @NotNull RunContentDescriptor descriptor) { + showRunContent(executor, descriptor, descriptor.getExecutionId()); } - public void showRunContent(@NotNull final Executor executor, final RunContentDescriptor descriptor, long executionId) { - if (ApplicationManager.getApplication().isUnitTestMode()) return; + public void showRunContent(@NotNull final Executor executor, @NotNull final RunContentDescriptor descriptor, long executionId) { + if (ApplicationManager.getApplication().isUnitTestMode()) { + return; + } final ContentManager contentManager = getContentManagerForRunner(executor); - RunContentDescriptor oldDescriptor = - chooseReuseContentForDescriptor(contentManager, descriptor, executionId, descriptor != null ? descriptor.getDisplayName() : null); - + RunContentDescriptor oldDescriptor = chooseReuseContentForDescriptor(contentManager, descriptor, executionId, descriptor.getDisplayName()); final Content content; - - Content oldAttachedContent = oldDescriptor != null ? oldDescriptor.getAttachedContent() : null; - if (oldDescriptor != null) { - content = oldAttachedContent; - getSyncPublisher().contentRemoved(oldDescriptor, executor); - Disposer.dispose(oldDescriptor); // is of the same category, can be reused - } - else if (oldAttachedContent == null || !oldAttachedContent.isValid() /*|| oldAttachedContent.getUserData(MARKED_TO_BE_REUSED) != null */) { + if (oldDescriptor == null) { content = createNewContent(contentManager, descriptor, executor); - final Icon icon = descriptor.getIcon(); + Icon icon = descriptor.getIcon(); content.setIcon(icon == null ? executor.getToolWindowIcon() : icon); - } else { - content = oldAttachedContent; } + else { + content = oldDescriptor.getAttachedContent(); + LOG.assertTrue(content != null); + getSyncPublisher().contentRemoved(oldDescriptor, executor); + Disposer.dispose(oldDescriptor); // is of the same category, can be reused + } + content.setExecutionId(executionId); content.setComponent(descriptor.getComponent()); content.setPreferredFocusedComponent(descriptor.getPreferredFocusComputable()); @@ -353,10 +324,10 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { if (!descriptor.isActivateToolWindowWhenAdded()) { return; } + ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { - if (myProject.isDisposed()) return; ToolWindow window = ToolWindowManager.getInstance(myProject).getToolWindow(executor.getToolWindowId()); // let's activate tool window, but don't move focus // @@ -367,14 +338,17 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { descriptor.getPreferredFocusComputable(); window.activate(null, descriptor.isAutoFocusContent(), descriptor.isAutoFocusContent()); } - }); + }, myProject.getDisposed()); } @Override @Nullable @Deprecated public RunContentDescriptor getReuseContent(final Executor requestor, DataContext dataContext) { - if (ApplicationManager.getApplication().isUnitTestMode()) return null; + if (ApplicationManager.getApplication().isUnitTestMode()) { + return null; + } + //noinspection deprecation return getReuseContent(requestor, GenericProgramRunner.CONTENT_TO_REUSE_DATA_KEY.getData(dataContext)); } @@ -382,11 +356,13 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { @Nullable @Deprecated public RunContentDescriptor getReuseContent(Executor requestor, @Nullable RunContentDescriptor contentToReuse) { - if (ApplicationManager.getApplication().isUnitTestMode()) return null; - if (contentToReuse != null) return contentToReuse; - - final ContentManager contentManager = getContentManagerForRunner(requestor); - return chooseReuseContentForDescriptor(contentManager, contentToReuse, 0L, null); + if (ApplicationManager.getApplication().isUnitTestMode()) { + return null; + } + if (contentToReuse != null) { + return contentToReuse; + } + return chooseReuseContentForDescriptor(getContentManagerForRunner(requestor), null, 0L, null); } @Nullable @@ -400,10 +376,12 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { public RunContentDescriptor getReuseContent(@NotNull ExecutionEnvironment executionEnvironment) { if (ApplicationManager.getApplication().isUnitTestMode()) return null; RunContentDescriptor contentToReuse = executionEnvironment.getContentToReuse(); - if (contentToReuse != null) return contentToReuse; + if (contentToReuse != null) { + return contentToReuse; + } final ContentManager contentManager = getContentManagerForRunner(executionEnvironment.getExecutor()); - return chooseReuseContentForDescriptor(contentManager, contentToReuse, executionEnvironment.getExecutionId(), + return chooseReuseContentForDescriptor(contentManager, null, executionEnvironment.getExecutionId(), executionEnvironment.toString()); } @@ -413,14 +391,21 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { } @Override - public void showRunContent(@NotNull final Executor info, RunContentDescriptor descriptor, RunContentDescriptor contentToReuse) { + public void showRunContent(@NotNull Executor info, @NotNull RunContentDescriptor descriptor, @Nullable RunContentDescriptor contentToReuse) { + copyContentAndBehavior(descriptor, contentToReuse); + showRunContent(info, descriptor, descriptor.getExecutionId()); + } + + public static void copyContentAndBehavior(@NotNull RunContentDescriptor descriptor, @Nullable RunContentDescriptor contentToReuse) { if (contentToReuse != null) { - final Content attachedContent = contentToReuse.getAttachedContent(); - if (attachedContent.getManager() != null) { + Content attachedContent = contentToReuse.getAttachedContent(); + if (attachedContent != null && attachedContent.isValid()) { descriptor.setAttachedContent(attachedContent); } + if (contentToReuse.isReuseToolWindowActivation()) { + descriptor.setActivateToolWindowWhenAdded(contentToReuse.isActivateToolWindowWhenAdded()); + } } - showRunContent(info, descriptor, descriptor != null ? descriptor.getExecutionId(): 0L); } @Nullable @@ -436,7 +421,9 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { } //Stage two: try to get content from descriptor itself final Content attachedContent = descriptor.getAttachedContent(); - if (attachedContent != null && attachedContent.isValid() && contentManager.getIndexOfContent(attachedContent) != -1) content = attachedContent; + if (attachedContent != null && attachedContent.isValid() && contentManager.getIndexOfContent(attachedContent) != -1) { + content = attachedContent; + } } //Stage three: choose the content with name we prefer if (content == null) { @@ -486,6 +473,7 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { if (contentManager == null) { LOG.error("Runner " + executor.getId() + " is not registered"); } + //noinspection ConstantConditions return contentManager; } @@ -499,26 +487,20 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { return content; } - private static boolean isTerminated(@NotNull final Content content) { - final RunContentDescriptor descriptor = getRunContentDescriptorByContent(content); - if (descriptor == null) { - return true; - } - else { - final ProcessHandler processHandler = descriptor.getProcessHandler(); - return processHandler == null || processHandler.isProcessTerminated(); - } + private static boolean isTerminated(@NotNull Content content) { + RunContentDescriptor descriptor = getRunContentDescriptorByContent(content); + ProcessHandler processHandler = descriptor == null ? null : descriptor.getProcessHandler(); + return processHandler == null || processHandler.isProcessTerminated(); } @Nullable - public static RunContentDescriptor getRunContentDescriptorByContent(@NotNull final Content content) { + private static RunContentDescriptor getRunContentDescriptorByContent(@NotNull Content content) { return content.getUserData(DESCRIPTOR_KEY); } - @Override @Nullable - public ToolWindow getToolWindowByDescriptor(@NotNull final RunContentDescriptor descriptor) { + public ToolWindow getToolWindowByDescriptor(@NotNull RunContentDescriptor descriptor) { for (Map.Entry<String, ContentManager> entry : myToolwindowIdToContentManagerMap.entrySet()) { if (getRunContentByDescriptor(entry.getValue(), descriptor) != null) { return ToolWindowManager.getInstance(myProject).getToolWindow(entry.getKey()); @@ -528,9 +510,8 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { } @Nullable - private static Content getRunContentByDescriptor(final ContentManager contentManager, final RunContentDescriptor descriptor) { - final Content[] contents = contentManager.getContents(); - for (final Content content : contents) { + private static Content getRunContentByDescriptor(@NotNull ContentManager contentManager, @NotNull RunContentDescriptor descriptor) { + for (Content content : contentManager.getContents()) { if (descriptor.equals(content.getUserData(DESCRIPTOR_KEY))) { return content; } @@ -539,18 +520,18 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { } @Override - public void addRunContentListener(final RunContentListener listener, final Executor executor) { + public void addRunContentListener(@NotNull final RunContentListener listener, final Executor executor) { final Disposable disposable = Disposer.newDisposable(); - myProject.getMessageBus().connect(disposable).subscribe(RUN_CONTENT_TOPIC, new RunContentWithExecutorListener() { + myProject.getMessageBus().connect(disposable).subscribe(TOPIC, new RunContentWithExecutorListener() { @Override - public void contentSelected(RunContentDescriptor descriptor, @NotNull Executor executor2) { + public void contentSelected(@Nullable RunContentDescriptor descriptor, @NotNull Executor executor2) { if (executor2.equals(executor)) { listener.contentSelected(descriptor); } } @Override - public void contentRemoved(RunContentDescriptor descriptor, @NotNull Executor executor2) { + public void contentRemoved(@Nullable RunContentDescriptor descriptor, @NotNull Executor executor2) { if (executor2.equals(executor)) { listener.contentRemoved(descriptor); } @@ -560,16 +541,16 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { } @Override - public void addRunContentListener(final RunContentListener listener) { + public void addRunContentListener(@NotNull final RunContentListener listener) { final Disposable disposable = Disposer.newDisposable(); - myProject.getMessageBus().connect(disposable).subscribe(RUN_CONTENT_TOPIC, new RunContentWithExecutorListener() { + myProject.getMessageBus().connect(disposable).subscribe(TOPIC, new RunContentWithExecutorListener() { @Override - public void contentSelected(RunContentDescriptor descriptor, @NotNull Executor executor) { + public void contentSelected(@Nullable RunContentDescriptor descriptor, @NotNull Executor executor) { listener.contentSelected(descriptor); } @Override - public void contentRemoved(RunContentDescriptor descriptor, @NotNull Executor executor) { + public void contentRemoved(@Nullable RunContentDescriptor descriptor, @NotNull Executor executor) { listener.contentRemoved(descriptor); } }); @@ -582,18 +563,16 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { if (myToolwindowIdToContentManagerMap.isEmpty()) { return Collections.emptyList(); } - final String[] ids = myToolwindowIdToContentManagerMap.keySet().toArray(new String[myToolwindowIdToContentManagerMap.size()]); - final List<RunContentDescriptor> descriptors = new ArrayList<RunContentDescriptor>(); - for (String id : ids) { - final ContentManager contentManager = myToolwindowIdToContentManagerMap.get(id); - for (final Content content : contentManager.getContents()) { - final RunContentDescriptor descriptor = getRunContentDescriptorByContent(content); + + List<RunContentDescriptor> descriptors = new SmartList<RunContentDescriptor>(); + for (String id : myToolwindowIdToContentManagerMap.keySet()) { + for (Content content : myToolwindowIdToContentManagerMap.get(id).getContents()) { + RunContentDescriptor descriptor = getRunContentDescriptorByContent(content); if (descriptor != null) { descriptors.add(descriptor); } } } - return descriptors; } @@ -607,10 +586,9 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { @Nullable private RunContentDescriptor getDescriptorBy(ProcessHandler handler, Executor runnerInfo) { - ContentManager contentManager = getContentManagerForRunner(runnerInfo); - Content[] contents = contentManager.getContents(); - for (Content content : contents) { - RunContentDescriptor runContentDescriptor = content.getUserData(DESCRIPTOR_KEY); + for (Content content : getContentManagerForRunner(runnerInfo).getContents()) { + RunContentDescriptor runContentDescriptor = getRunContentDescriptorByContent(content); + assert runContentDescriptor != null; if (runContentDescriptor.getProcessHandler() == handler) { return runContentDescriptor; } @@ -642,12 +620,11 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { final Content content = myContent; try { - final RunContentDescriptor descriptor = getRunContentDescriptorByContent(content); - + RunContentDescriptor descriptor = getRunContentDescriptorByContent(content); getSyncPublisher().contentRemoved(descriptor, myExecutor); - - if (descriptor != null) + if (descriptor != null) { Disposer.dispose(descriptor); + } } finally { content.getManager().removeContentManagerListener(this); @@ -699,7 +676,6 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { private boolean closeQuery(boolean modal) { final RunContentDescriptor descriptor = getRunContentDescriptorByContent(myContent); - if (descriptor == null) { return true; } @@ -709,6 +685,7 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { return true; } final boolean destroyProcess; + //noinspection deprecation if (processHandler.isSilentlyDestroyOnClose() || Boolean.TRUE.equals(processHandler.getUserData(ProcessHandler.SILENTLY_DESTROY_ON_CLOSE))) { destroyProcess = true; } @@ -786,7 +763,9 @@ public class RunContentManagerImpl implements RunContentManager, Disposable { break; } try { + //noinspection SynchronizeOnThis synchronized (this) { + //noinspection SynchronizeOnThis wait(2000L); } } diff --git a/platform/lang-impl/src/com/intellij/execution/ui/RunContentWithExecutorListener.java b/platform/lang-impl/src/com/intellij/execution/ui/RunContentWithExecutorListener.java deleted file mode 100644 index 8231f0d1d1d8..000000000000 --- a/platform/lang-impl/src/com/intellij/execution/ui/RunContentWithExecutorListener.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2000-2010 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.execution.ui; - -import com.intellij.execution.Executor; -import org.jetbrains.annotations.NotNull; - -/** - * @author nik - */ -public interface RunContentWithExecutorListener { - void contentSelected(RunContentDescriptor descriptor, @NotNull Executor executor); - void contentRemoved(RunContentDescriptor descriptor, @NotNull Executor executor); -} 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 b70d37a79e41..301cceee7e19 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 @@ -70,6 +70,7 @@ public class GridCellImpl implements GridCell { myPlaceInGrid = placeInGrid; myPlaceholder = placeholder; myTabs = new JBTabsImpl(myContext.getProject(), myContext.getActionManager(), myContext.getFocusManager(), container) { + @SuppressWarnings("UseJBColor") @Override protected Color getFocusedTopFillColor() { return UIUtil.isUnderDarcula() ? ColorUtil.toAlpha(new Color(0x1E2533), 100) : new Color(202, 211, 227); @@ -88,11 +89,13 @@ public class GridCellImpl implements GridCell { super.paintBorder(g2d, shape, borderColor); } + @SuppressWarnings("UseJBColor") @Override protected Color getFocusedBottomFillColor() { return UIUtil.isUnderDarcula() ? new Color(0x1E2533) : new Color(0xc2cbdb); } + @SuppressWarnings("UseJBColor") @Override public Color getBackground() { return UIUtil.isUnderDarcula() ? new Color(0x27292A) : super.getBackground(); @@ -239,8 +242,6 @@ public class GridCellImpl implements GridCell { } private TabInfo createTabInfoFor(Content content) { - final JComponent c = content.getComponent(); - final TabInfo tabInfo = updatePresentation(new TabInfo(new ProviderWrapper(content, myContext)), content) .setObject(content) .setPreferredFocusableComponent(content.getPreferredFocusableComponent()) @@ -257,7 +258,10 @@ public class GridCellImpl implements GridCell { @Nullable private static TabInfo updatePresentation(TabInfo info, Content content) { - if (info == null) return info; + if (info == null) { + return null; + } + return info. setIcon(content.getIcon()). setText(content.getDisplayName()). @@ -309,7 +313,6 @@ public class GridCellImpl implements GridCell { } private static class ProviderWrapper extends NonOpaquePanel implements DataProvider { - Content myContent; ViewContext myContext; diff --git a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/JBRunnerTabs.java b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/JBRunnerTabs.java index 8ca416bd5427..d680e8a7e173 100644 --- a/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/JBRunnerTabs.java +++ b/platform/lang-impl/src/com/intellij/execution/ui/layout/impl/JBRunnerTabs.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ import java.util.Map; */ public class JBRunnerTabs extends JBTabsImpl { - public JBRunnerTabs(@Nullable Project project, ActionManager actionManager, IdeFocusManager focusManager, @NotNull Disposable parent) { + public JBRunnerTabs(@Nullable Project project, @NotNull ActionManager actionManager, IdeFocusManager focusManager, @NotNull Disposable parent) { super(project, actionManager, focusManager, parent); } 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 821d9dbd6bc3..b8225b0c238b 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 @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,7 +89,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac private ContentManager myManager; private final RunnerLayout myLayoutSettings; - private final ActionManager myActionManager; + @NotNull private final ActionManager myActionManager; private final String mySessionName; private final MyComponent myComponent = new MyComponent(); @@ -99,7 +99,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac JBRunnerTabs myTabs; private final Comparator<TabInfo> myTabsComparator = new Comparator<TabInfo>() { @Override - public int compare(final TabInfo o1, final TabInfo o2) { + public int compare(@NotNull final TabInfo o1, @NotNull final TabInfo o2) { //noinspection ConstantConditions TabImpl tab1 = getTabFor(o1); TabImpl tab2 = getTabFor(o2); @@ -132,7 +132,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac private final Map<String, LayoutAttractionPolicy> myConditionAttractions = new HashMap<String, LayoutAttractionPolicy>(); private ActionGroup myTabPopupActions; - private ActionGroup myAdditonalFocusActions; + private ActionGroup myAdditionalFocusActions; private final ActionCallback myInitialized = new ActionCallback(); private boolean myToDisposeRemovedContent = true; @@ -149,7 +149,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac private final CopyOnWriteArraySet<Listener> myDockingListeners = new CopyOnWriteArraySet<Listener>(); private final Set<RunnerContentUi> myChildren = new TreeSet<RunnerContentUi>(new Comparator<RunnerContentUi>() { @Override - public int compare(RunnerContentUi o1, RunnerContentUi o2) { + public int compare(@NotNull RunnerContentUi o1, @NotNull RunnerContentUi o2) { return o1.myWindow - o2.myWindow; } }); @@ -164,7 +164,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac @NotNull String sessionName) { myProject = project; myRunnerUi = ui; - myLayoutSettings = settings; + myLayoutSettings = settings; myActionManager = actionManager; mySessionName = sessionName; myFocusManager = focusManager; @@ -190,7 +190,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac } public void setAdditionalFocusActions(final ActionGroup group) { - myAdditonalFocusActions = group; + myAdditionalFocusActions = group; rebuildTabPopup(); } @@ -269,7 +269,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac }); myTabs.addTabMouseListener(new MouseAdapter() { @Override - public void mousePressed(MouseEvent e) { + public void mousePressed(@NotNull MouseEvent e) { if (UIUtil.isCloseClick(e)) { final TabInfo tabInfo = myTabs.findInfo(e); final GridImpl grid = tabInfo == null? null : getGridFor(tabInfo); @@ -299,10 +299,11 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac } private void rebuildTabPopup() { + initUi(); + myTabs.setPopupGroup(getCellPopupGroup(TAB_POPUP_PLACE), TAB_POPUP_PLACE, true); - final ArrayList<GridImpl> grids = getGrids(); - for (GridImpl each : grids) { + for (GridImpl each : getGrids()) { each.rebuildTabPopup(); } } @@ -325,10 +326,9 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac for (AnAction eachFocus : focusActions) { group.add(eachFocus); } - if (myAdditonalFocusActions != null) { - final AnAction[] addins = myAdditonalFocusActions.getChildren(event); - for (AnAction eachAddin : addins) { - group.add(eachAddin); + if (myAdditionalFocusActions != null) { + for (AnAction action : myAdditionalFocusActions.getChildren(event)) { + group.add(action); } } } @@ -350,7 +350,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac } @Override - public void propertyChange(final PropertyChangeEvent evt) { + public void propertyChange(@NotNull final PropertyChangeEvent evt) { Content content = (Content)evt.getSource(); final GridImpl grid = getGridFor(content, false); if (grid == null) return; @@ -436,8 +436,8 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac return new ActionCallback.Done(); } - private void storeDefaultIndices(Content[] contents) { - int i = 0; + private void storeDefaultIndices(@NotNull Content[] contents) { + //int i = 0; for (Content content : contents) { content.putUserData(RunnerLayout.DEFAULT_INDEX, getStateFor(content).getTab().getDefaultIndex()); //content.putUserData(CONTENT_NUMBER, i++); @@ -637,8 +637,9 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac myManager.addContentManagerListener(new ContentManagerListener() { @Override public void contentAdded(final ContentManagerEvent event) { - final GridImpl grid = getGridFor(event.getContent(), true); + initUi(); + GridImpl grid = getGridFor(event.getContent(), true); if (grid == null) { return; } @@ -795,10 +796,12 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac private static void moveFollowingTabs(int index, final JBRunnerTabs tabs) { for (TabInfo info : tabs.getTabs()) { - final TabImpl tab = getTabFor(info); - final int tabIndex = tab != null ? tab.getIndex() : -1; - if (tabIndex >= index) { - tab.setIndex(tabIndex + 1); + TabImpl tab = getTabFor(info); + if (tab != null) { + int tabIndex = tab.getIndex(); + if (tabIndex >= index) { + tab.setIndex(tabIndex + 1); + } } } } @@ -1147,7 +1150,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac myOriginal = null; myTopActions = null; - myAdditonalFocusActions = null; + myAdditionalFocusActions = null; myLeftToolbarActions = null; } @@ -1166,7 +1169,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac Content[] all = contents.toArray(new Content[contents.size()]); Arrays.sort(all, new Comparator<Content>() { @Override - public int compare(Content content, Content content1) { + public int compare(@NotNull Content content, @NotNull Content content1) { final int i = getStateFor(content).getTab().getDefaultIndex(); final int i1 = getStateFor(content1).getTab().getDefaultIndex(); return i - i1; @@ -1222,6 +1225,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac myMinimizeActionEnabled = enabled; } + @SuppressWarnings("SpellCheckingInspection") public void setMovetoGridActionEnabled(final boolean enabled) { myMoveToGridActionEnabled = enabled; } @@ -1271,7 +1275,6 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac return null; } - @Nullable public void restoreContent(final String key) { for (AnAction action : myMinimizedViewActions.getChildren(null)) { Content content = ((RestoreViewAction)action).getContent(); @@ -1293,7 +1296,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac private static class MyDropAreaPainter extends AbstractPainter { private Shape myBoundingBox; - private Color myColor = ColorUtil.mix(JBColor.BLUE, JBColor.WHITE, .3); + private final Color myColor = ColorUtil.mix(JBColor.BLUE, JBColor.WHITE, .3); @Override public boolean needsRepaint() { @@ -1390,6 +1393,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac } } + @SuppressWarnings("NullableProblems") @Override public String getName() { return RunnerContentUi.this.getName(); @@ -1575,6 +1579,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac return myManager; } + @NotNull @Override public ActionManager getActionManager() { return myActionManager; @@ -1617,7 +1622,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac } @Override - public void validate(final Content content, final ActiveRunnable toRestore) { + public void validate(Content content, final ActiveRunnable toRestore) { final TabInfo current = myTabs.getSelectedInfo(); myTabs.getPresentation().setPaintBlocked(true, true); @@ -1628,6 +1633,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac toRestore.run().doWhenDone(new Runnable() { @Override public void run() { + assert current != null; myTabs.select(current, true); myTabs.getPresentation().setPaintBlocked(false, true); } @@ -1654,7 +1660,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac } @Override - public Dimension preferredLayoutSize(final Container parent) { + public Dimension preferredLayoutSize(@NotNull final Container parent) { Dimension size = new Dimension(); Dimension leftSize = myLeft.getPreferredSize(); @@ -1667,7 +1673,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac } @Override - public void layoutContainer(final Container parent) { + public void layoutContainer(@NotNull final Container parent) { Dimension size = parent.getSize(); Dimension prefSize = parent.getPreferredSize(); if (prefSize.width <= size.width) { @@ -1806,10 +1812,9 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac @Override public void dragOutStarted(MouseEvent mouseEvent, TabInfo info) { - final JComponent component = info.getComponent(); - final Content[] data = CONTENT_KEY.getData((DataProvider)component); - final List<Content> contents = Arrays.asList(data); - + JComponent component = info.getComponent(); + Content[] data = CONTENT_KEY.getData((DataProvider)component); + assert data != null; storeDefaultIndices(data); final Dimension size = info.getComponent().getSize(); @@ -1822,7 +1827,7 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac presentation.setIcon(info.getIcon()); mySession = getDockManager().createDragSession(mouseEvent, new DockableGrid(image, presentation, size, - contents, 0)); + Arrays.asList(data), 0)); } @Override 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 70d6a3f92819..7475adbcab21 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 @@ -21,7 +21,6 @@ import com.intellij.execution.ui.layout.LayoutAttractionPolicy; import com.intellij.execution.ui.layout.LayoutStateDefaults; import com.intellij.execution.ui.layout.LayoutViewOptions; import com.intellij.execution.ui.layout.PlaceInGrid; -import com.intellij.ide.DataManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.ActionManager; @@ -46,9 +45,8 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; -public class RunnerLayoutUiImpl implements Disposable.Parent, RunnerLayoutUi, LayoutStateDefaults, LayoutViewOptions { +public class RunnerLayoutUiImpl implements Disposable.Parent, RunnerLayoutUi, LayoutStateDefaults, LayoutViewOptions, DataProvider { private final RunnerLayout myLayout; - private final JPanel myContentPanel; private final RunnerContentUi myContentUI; private final ContentManager myViewsContentManager; @@ -63,14 +61,12 @@ public class RunnerLayoutUiImpl implements Disposable.Parent, RunnerLayoutUi, La Disposer.register(parent, this); myContentUI = new RunnerContentUi(project, this, ActionManager.getInstance(), IdeFocusManager.getInstance(project), myLayout, - runnerTitle + " - " + sessionName); + runnerTitle + " - " + sessionName); Disposer.register(this, myContentUI); - myContentPanel = new MyContent(); myViewsContentManager = getContentFactory().createContentManager(myContentUI.getContentUI(), false, project); + myViewsContentManager.addDataProvider(this); Disposer.register(this, myViewsContentManager); - - myContentPanel.add(myViewsContentManager.getComponent(), BorderLayout.CENTER); } @Override @@ -80,7 +76,6 @@ public class RunnerLayoutUiImpl implements Disposable.Parent, RunnerLayoutUi, La return this; } - @NotNull @Override public LayoutStateDefaults initTabDefaults(int id, String text, Icon icon) { @@ -156,7 +151,7 @@ public class RunnerLayoutUiImpl implements Disposable.Parent, RunnerLayoutUi, La @Override @NotNull public JComponent getComponent() { - return myContentPanel; + return myViewsContentManager.getComponent(); } private static ContentFactory getContentFactory() { @@ -380,28 +375,12 @@ public class RunnerLayoutUiImpl implements Disposable.Parent, RunnerLayoutUi, La return contents; } - private class MyContent extends JPanel implements DataProvider { - public MyContent() { - super(new BorderLayout()); - } - - @Override - public Object getData(@NonNls String dataId) { - if (SwitchProvider.KEY.getName().equals(dataId)) { - return myContentUI; - } - - if (QuickActionProvider.KEY.getName().equals(dataId)) { - return myContentUI; - } - - if (RunnerContentUi.KEY.getName().equals(dataId)) { - return myContentUI; - } - - final DataProvider provider = DataManager.getDataProvider(this); - return provider != null ? provider.getData(dataId) : null; + @Nullable + @Override + public Object getData(@NonNls String dataId) { + if (SwitchProvider.KEY.is(dataId) || QuickActionProvider.KEY.is(dataId) || RunnerContentUi.KEY.is(dataId)) { + return myContentUI; } + return null; } - } diff --git a/platform/lang-impl/src/com/intellij/find/FindSettings.java b/platform/lang-impl/src/com/intellij/find/FindSettings.java index d61fd395eadd..d8c6d73461a1 100644 --- a/platform/lang-impl/src/com/intellij/find/FindSettings.java +++ b/platform/lang-impl/src/com/intellij/find/FindSettings.java @@ -128,4 +128,7 @@ public abstract class FindSettings{ public abstract boolean isExceptCommentsAndLiterals(); public abstract void setExceptCommentsAndLiterals(boolean selected); + + public abstract boolean isShowResultsInSeparateView(); + public abstract void setShowResultsInSeparateView(boolean selected); } diff --git a/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesTableCellRenderer.java b/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesTableCellRenderer.java index d9848fdec4b0..c4445c4ab5d2 100644 --- a/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesTableCellRenderer.java +++ b/platform/lang-impl/src/com/intellij/find/actions/ShowUsagesTableCellRenderer.java @@ -77,7 +77,7 @@ class ShowUsagesTableCellRenderer implements TableCellRenderer { textChunks.setBorder(null); if (usage == null || usageNode instanceof ShowUsagesAction.StringNode) { - textChunks.append(value.toString(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); + textChunks.append(value != null ? value.toString() : "", SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); return textComponentSpanningWholeRow(textChunks, panelBackground, panelForeground, column, list, row); } if (usage == ShowUsagesAction.MORE_USAGES_SEPARATOR) { diff --git a/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java b/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java index d7f7665a9299..b78ce2c7ead7 100644 --- a/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java +++ b/platform/lang-impl/src/com/intellij/find/findInProject/FindInProjectManager.java @@ -40,7 +40,6 @@ import org.jetbrains.annotations.NotNull; public class FindInProjectManager { private final Project myProject; - private boolean myToOpenInNewTab = false; private volatile boolean myIsFindInProgress = false; public static FindInProjectManager getInstance(Project project) { @@ -60,12 +59,12 @@ public class FindInProjectManager { isOpenInNewTabEnabled = false; } else { - toOpenInNewTab[0] = myToOpenInNewTab; + toOpenInNewTab[0] = FindSettings.getInstance().isShowResultsInSeparateView(); isOpenInNewTabEnabled = UsageViewManager.getInstance(myProject).getReusableContentsCount() > 0; } final FindManager findManager = FindManager.getInstance(myProject); - final FindModel findModel = (FindModel) findManager.getFindInProjectModel().clone(); + final FindModel findModel = findManager.getFindInProjectModel().clone(); findModel.setReplaceState(false); findModel.setOpenInNewTabVisible(true); findModel.setOpenInNewTabEnabled(isOpenInNewTabEnabled); @@ -86,7 +85,7 @@ public class FindInProjectManager { public void run() { findModel.setOpenInNewTabVisible(false); if (isOpenInNewTabEnabled) { - myToOpenInNewTab = toOpenInNewTab[0] = findModel.isOpenInNewTab(); + FindSettings.getInstance().setShowResultsInSeparateView(toOpenInNewTab[0] = findModel.isOpenInNewTab()); } startFindInProject(findModel); @@ -107,8 +106,8 @@ public class FindInProjectManager { if (manager == null) return; final FindManager findManager = FindManager.getInstance(myProject); findManager.getFindInProjectModel().copyFrom(findModel); - final FindModel findModelCopy = (FindModel)findModel.clone(); - final UsageViewPresentation presentation = FindInProjectUtil.setupViewPresentation(myToOpenInNewTab, findModelCopy); + final FindModel findModelCopy = findModel.clone(); + final UsageViewPresentation presentation = FindInProjectUtil.setupViewPresentation(FindSettings.getInstance().isShowResultsInSeparateView(), findModelCopy); final boolean showPanelIfOnlyOneUsage = !FindSettings.getInstance().isSkipResultsWithOneUsage(); final FindUsagesProcessPresentation processPresentation = FindInProjectUtil.setupProcessPresentation(myProject, showPanelIfOnlyOneUsage, presentation); diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindDialog.java b/platform/lang-impl/src/com/intellij/find/impl/FindDialog.java index c25456da1988..b268e455a67c 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/FindDialog.java +++ b/platform/lang-impl/src/com/intellij/find/impl/FindDialog.java @@ -45,10 +45,7 @@ import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.search.SearchScope; -import com.intellij.ui.EditorComboBoxRenderer; -import com.intellij.ui.EditorTextField; -import com.intellij.ui.IdeBorderFactory; -import com.intellij.ui.StateRestoringCheckBox; +import com.intellij.ui.*; import com.intellij.util.ArrayUtil; import com.intellij.util.Consumer; import com.intellij.util.ui.UIUtil; @@ -340,6 +337,9 @@ public class FindDialog extends DialogWrapper { topOptionsPanel.setLayout(new GridLayout(1, 2, UIUtil.DEFAULT_HGAP, 0)); topOptionsPanel.add(createFindOptionsPanel()); optionsPanel.add(topOptionsPanel, gbConstraints); + + JPanel resultsOptionPanel = null; + if (myModel.isMultipleFiles()) { optionsPanel.add(createGlobalScopePanel(), gbConstraints); gbConstraints.weightx = 1; @@ -350,7 +350,9 @@ public class FindDialog extends DialogWrapper { optionsPanel.add(createFilterPanel(),gbConstraints); myCbToSkipResultsWhenOneUsage = createCheckbox(FindSettings.getInstance().isSkipResultsWithOneUsage(), FindBundle.message("find.options.skip.results.tab.with.one.occurrence.checkbox")); - optionsPanel.add(myCbToSkipResultsWhenOneUsage, gbConstraints); + resultsOptionPanel = createResultsOptionPanel(optionsPanel, gbConstraints); + resultsOptionPanel.add(myCbToSkipResultsWhenOneUsage); + myCbToSkipResultsWhenOneUsage.setVisible(!myModel.isReplaceState()); } else { @@ -374,18 +376,26 @@ public class FindDialog extends DialogWrapper { } if (myModel.isOpenInNewTabVisible()){ - JPanel openInNewTabWindowPanel = new JPanel(new BorderLayout()); myCbToOpenInNewTab = new JCheckBox(FindBundle.message("find.open.in.new.tab.checkbox")); myCbToOpenInNewTab.setFocusable(false); myCbToOpenInNewTab.setSelected(myModel.isOpenInNewTab()); myCbToOpenInNewTab.setEnabled(myModel.isOpenInNewTabEnabled()); - openInNewTabWindowPanel.add(myCbToOpenInNewTab, BorderLayout.EAST); - optionsPanel.add(openInNewTabWindowPanel, gbConstraints); + + if (resultsOptionPanel == null) resultsOptionPanel = createResultsOptionPanel(optionsPanel, gbConstraints); + resultsOptionPanel.add(myCbToOpenInNewTab); } return optionsPanel; } + private static JPanel createResultsOptionPanel(JPanel optionsPanel, GridBagConstraints gbConstraints) { + JPanel resultsOptionPanel = new JPanel(); + resultsOptionPanel.setLayout(new BoxLayout(resultsOptionPanel, BoxLayout.Y_AXIS)); + + optionsPanel.add(new HideableTitledPanel(FindBundle.message("results.options.group"), resultsOptionPanel, false), gbConstraints); + return resultsOptionPanel; + } + @NotNull private JComponent createFilterPanel() { JPanel filterPanel = new JPanel(); @@ -615,9 +625,11 @@ public class FindDialog extends DialogWrapper { JLabel searchContextLabel = new JLabel(FindBundle.message("find.context.combo.label")); searchContextLabel.setLabelFor(mySearchContext); - searchContextPanel.add(searchContextLabel, BorderLayout.WEST); - - searchContextPanel.add(mySearchContext, BorderLayout.CENTER); + JPanel panel = new JPanel(); + panel.setAlignmentX(Component.LEFT_ALIGNMENT); + panel.add(searchContextLabel); + panel.add(mySearchContext); + searchContextPanel.add(panel, BorderLayout.WEST); if (FindManagerImpl.ourHasSearchInCommentsAndLiterals) { findOptionsPanel.add(searchContextPanel); diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java b/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java index 23f14c5eb0b4..db82791478f0 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java +++ b/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java @@ -301,6 +301,7 @@ public class FindInProjectUtil { } presentation.setOpenInNewTab(toOpenInNewTab); presentation.setCodeUsages(false); + presentation.setUsageTypeFilteringAvailable(true); return presentation; } diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java b/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java index 27e2b7215f25..b7d58e926e30 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java @@ -387,7 +387,8 @@ public class FindManagerImpl extends FindManager implements PersistentStateCompo if (input == null || !input.isStringFound()) return true; NavigableMap<Integer, Integer> map = mySkipRangesSet.headMap(input.getStartOffset(), true); for(Map.Entry<Integer, Integer> e:map.descendingMap().entrySet()) { - if (e.getKey() <= input.getStartOffset() && e.getValue() >= input.getEndOffset()) return false; + // [e.key, e.value] intersect with [input.start, input.end] + if (e.getKey() <= input.getStartOffset() && (input.getStartOffset() <= e.getValue() || e.getValue() >= input.getEndOffset())) return false; if (e.getValue() <= input.getStartOffset()) break; } return true; diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindSettingsImpl.java b/platform/lang-impl/src/com/intellij/find/impl/FindSettingsImpl.java index c9c8e3492834..ffe3555ea059 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/FindSettingsImpl.java +++ b/platform/lang-impl/src/com/intellij/find/impl/FindSettingsImpl.java @@ -110,6 +110,7 @@ public class FindSettingsImpl extends FindSettings implements PersistentStateCom @SuppressWarnings({"WeakerAccess"}) public boolean REGULAR_EXPRESSIONS = false; @SuppressWarnings({"WeakerAccess"}) public boolean LOCAL_REGULAR_EXPRESSIONS = false; @SuppressWarnings({"WeakerAccess"}) public boolean WITH_SUBDIRECTORIES = true; + @SuppressWarnings({"WeakerAccess"}) public boolean SHOW_RESULTS_IN_SEPARATE_VIEW = false; @SuppressWarnings({"WeakerAccess"}) public String SEARCH_SCOPE = DEFAULT_SEARCH_SCOPE; @SuppressWarnings({"WeakerAccess"}) public String FILE_MASK; @@ -409,6 +410,16 @@ public class FindSettingsImpl extends FindSettings implements PersistentStateCom } @Override + public boolean isShowResultsInSeparateView() { + return SHOW_RESULTS_IN_SEPARATE_VIEW; + } + + @Override + public void setShowResultsInSeparateView(boolean optionValue) { + SHOW_RESULTS_IN_SEPARATE_VIEW = optionValue; + } + + @Override public boolean isExceptCommentsAndLiterals() { return EXCEPT_COMMENTS_AND_STRING_LITERALS; } diff --git a/platform/lang-impl/src/com/intellij/formatting/FormatProcessor.java b/platform/lang-impl/src/com/intellij/formatting/FormatProcessor.java index 7d3c7c649fd2..73358455bdcd 100644 --- a/platform/lang-impl/src/com/intellij/formatting/FormatProcessor.java +++ b/platform/lang-impl/src/com/intellij/formatting/FormatProcessor.java @@ -180,6 +180,7 @@ class FormatProcessor { } private int getRightMargin(Block rootBlock) { + Language language = null; if (rootBlock instanceof ASTBlock) { ASTNode node = ((ASTBlock)rootBlock).getNode(); if (node != null) { @@ -187,12 +188,12 @@ class FormatProcessor { if (psiElement.isValid()) { PsiFile psiFile = psiElement.getContainingFile(); if (psiFile != null) { - return mySettings.getRightMargin(psiFile.getViewProvider().getBaseLanguage()); + language = psiFile.getViewProvider().getBaseLanguage(); } } } } - return mySettings.RIGHT_MARGIN; + return mySettings.getRightMargin(language); } private LeafBlockWrapper getLastBlock() { diff --git a/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java b/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java index 7b40b786ff7a..5b32caed587d 100644 --- a/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java +++ b/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java @@ -112,26 +112,27 @@ public class FormatterImpl extends FormatterEx @Override public int getSpacingForBlockAtOffset(FormattingModel model, int offset) { Couple<Block> blockWithParent = getBlockAtOffset(null, model.getRootBlock(), offset); - if (blockWithParent == null) { - return 0; - } - Block parentBlock = blockWithParent.first; - Block targetBlock = blockWithParent.second; - if (parentBlock == null || targetBlock == null) { - return 0; - } - Block prevBlock = findPreviousSibling(parentBlock, targetBlock); - if (prevBlock == null) { - return 0; - } - SpacingImpl spacing = (SpacingImpl)parentBlock.getSpacing(prevBlock, targetBlock); - if (spacing == null) { - return 0; + if (blockWithParent != null) { + Block parentBlock = blockWithParent.first; + Block targetBlock = blockWithParent.second; + if (parentBlock != null && targetBlock != null) { + Block prevBlock = findPreviousSibling(parentBlock, targetBlock); + if (prevBlock != null) { + SpacingImpl spacing = (SpacingImpl)parentBlock.getSpacing(prevBlock, targetBlock); + if (spacing != null) { + int minSpaces = spacing.getMinSpaces(); + if (minSpaces > 0) { + return minSpaces; + } + } + } + } } - return Math.max(spacing.getMinSpaces(), 0); + return 0; } - private static Couple<Block> getBlockAtOffset(Block parent, Block block, int offset) { + @Nullable + private static Couple<Block> getBlockAtOffset(@Nullable Block parent, @NotNull Block block, int offset) { TextRange textRange = block.getTextRange(); int startOffset = textRange.getStartOffset(); int endOffset = textRange.getEndOffset(); @@ -150,7 +151,8 @@ public class FormatterImpl extends FormatterEx return null; } - private static Block findPreviousSibling(Block parent, Block block) { + @Nullable + private static Block findPreviousSibling(@NotNull Block parent, Block block) { Block result = null; for (Block subBlock : parent.getSubBlocks()) { if (subBlock == block) { @@ -568,6 +570,7 @@ public class FormatterImpl extends FormatterEx final TextRange affectedRange) { final FormattingDocumentModel documentModel = model.getDocumentModel(); final Block block = model.getRootBlock(); + if (block.getTextRange().isEmpty()) return null; // handing empty document case final FormatProcessor processor = buildProcessorAndWrapBlocks( documentModel, block, settings, indentOptions, new FormatTextRanges(affectedRange, true), offset ); diff --git a/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java b/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java index d704e738efa3..bfd00da9107d 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java @@ -18,9 +18,11 @@ package com.intellij.ide.actions; import com.intellij.codeInsight.navigation.NavigationUtil; import com.intellij.execution.Executor; import com.intellij.execution.ExecutorRegistry; +import com.intellij.execution.RunnerAndConfigurationSettings; import com.intellij.execution.actions.ChooseRunConfigurationPopup; import com.intellij.execution.actions.ExecutorProvider; import com.intellij.execution.executors.DefaultRunExecutor; +import com.intellij.execution.impl.RunDialog; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; @@ -116,7 +118,7 @@ import java.util.concurrent.atomic.AtomicBoolean; * @author Konstantin Bulenkov */ @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") -public class SearchEverywhereAction extends AnAction implements CustomComponentAction, DumbAware{ +public class SearchEverywhereAction extends AnAction implements CustomComponentAction, DumbAware, DataProvider, RightAlignedToolbarAction { public static final String SE_HISTORY_KEY = "SearchEverywhereHistoryKey"; public static final int SEARCH_FIELD_COLUMNS = 25; private static final int MAX_CLASSES = 6; @@ -321,6 +323,12 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA } + @Nullable + @Override + public Object getData(@NonNls String dataId) { + return null; + } + private static String getShortcut() { String shortcutText; final Shortcut[] shortcuts = KeymapManager.getInstance().getActiveKeymap().getShortcuts(IdeActions.ACTION_SEARCH_EVERYWHERE); @@ -673,6 +681,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA panel.add(myPopupField, BorderLayout.CENTER); panel.add(topPanel, BorderLayout.NORTH); panel.setBorder(IdeBorderFactory.createEmptyBorder(3, 5, 4, 5)); + DataManager.registerDataProvider(panel, this); final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, editor); myBalloon = builder .setCancelOnClickOutside(true) @@ -695,7 +704,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA }); Component parent = UIUtil.findUltimateParent(window); - registerDataProvider(panel); + registerDataProvider(panel, e.getProject()); final RelativePoint showPoint; if (me != null) { final Component label = me.getComponent(); @@ -773,7 +782,12 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA storage.setValues(SE_HISTORY_KEY, newValues); } - private void registerDataProvider(JPanel panel) { + public Executor getExecutor() { + return ourShiftIsPressed.get() ? DefaultRunExecutor.getRunExecutorInstance() + : ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG); + } + + private void registerDataProvider(JPanel panel, final Project project) { DataManager.registerDataProvider(panel, new DataProvider() { @Nullable @Override @@ -783,6 +797,29 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA return value; } else if (CommonDataKeys.VIRTUAL_FILE.is(dataId) && value instanceof VirtualFile) { return value; + } else if (CommonDataKeys.NAVIGATABLE.is(dataId)) { + if (value instanceof Navigatable) return value; + if (value instanceof ChooseRunConfigurationPopup.ItemWrapper) { + final Object config = ((ChooseRunConfigurationPopup.ItemWrapper)value).getValue(); + if (config instanceof RunnerAndConfigurationSettings) { + return new Navigatable() { + @Override + public void navigate(boolean requestFocus) { + RunDialog.editConfiguration(project, (RunnerAndConfigurationSettings)config, "Edit Configuration", getExecutor()); + } + + @Override + public boolean canNavigate() { + return true; + } + + @Override + public boolean canNavigateToSource() { + return true; + } + }; + } + } } return null; } diff --git a/platform/lang-impl/src/com/intellij/ide/actions/SelectInAction.java b/platform/lang-impl/src/com/intellij/ide/actions/SelectInAction.java index 7efdfb14249f..55d532106a56 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/SelectInAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/SelectInAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ public class SelectInAction extends AnAction implements DumbAware { } } - private static void invoke(DataContext dataContext, SelectInContext context) { + private static void invoke(@NotNull DataContext dataContext, @NotNull SelectInContext context) { final List<SelectInTarget> targetVector = Arrays.asList(getSelectInManager(context.getProject()).getTargets()); ListPopup popup; if (targetVector.isEmpty()) { @@ -71,10 +71,10 @@ public class SelectInAction extends AnAction implements DumbAware { } private static class SelectInActionsStep extends BaseListPopupStep<SelectInTarget> { - private final SelectInContext mySelectInContext; + @NotNull private final SelectInContext mySelectInContext; private final List<SelectInTarget> myVisibleTargets; - public SelectInActionsStep(@NotNull final Collection<SelectInTarget> targetVector, SelectInContext selectInContext) { + public SelectInActionsStep(@NotNull final Collection<SelectInTarget> targetVector, @NotNull SelectInContext selectInContext) { mySelectInContext = selectInContext; myVisibleTargets = new ArrayList<SelectInTarget>(); for (SelectInTarget target : targetVector) { diff --git a/platform/lang-impl/src/com/intellij/ide/commander/CommanderPanel.java b/platform/lang-impl/src/com/intellij/ide/commander/CommanderPanel.java index b5af4621705d..03a5a7fd806a 100644 --- a/platform/lang-impl/src/com/intellij/ide/commander/CommanderPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/commander/CommanderPanel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -607,6 +607,7 @@ public class CommanderPanel extends JPanel { } } + @NotNull @Override public PsiDirectory[] getDirectories() { PsiDirectory directory = getDirectory(); diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesProjectViewPane.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesProjectViewPane.java index c76416e5a4b1..df2a1bf83962 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesProjectViewPane.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesProjectViewPane.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,6 +131,7 @@ public class FavoritesProjectViewPane extends AbstractProjectViewPane { return subId; } + @NotNull @Override public ActionCallback updateFromRoot(boolean restoreExpandedPaths) { return ((FavoritesViewTreeBuilder)getTreeBuilder()).updateFromRootCB(); diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeViewPanel.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeViewPanel.java index f97eb9e2a8df..4d72b483a39c 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeViewPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesTreeViewPanel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -777,6 +777,7 @@ public class FavoritesTreeViewPanel extends JPanel implements DataProvider, Dock return selectedNodeElements[0] instanceof PsiDirectory ? new PsiDirectory[]{(PsiDirectory)selectedNodeElements[0]} : null; } + @NotNull @Override public PsiDirectory[] getDirectories() { final PsiDirectory[] directories = getSelectedDirectories(); 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 8b96157234d8..a0fb4f5d389d 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-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import java.util.LinkedHashSet; public class ProjectViewSelectInGroupTarget implements CompositeSelectInTarget, DumbAware { @Override @NotNull - public Collection<SelectInTarget> getSubTargets(SelectInContext context) { + public Collection<SelectInTarget> getSubTargets(@NotNull SelectInContext context) { return ProjectView.getInstance(context.getProject()).getSelectInTargets(); } diff --git a/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInTarget.java b/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInTarget.java index 8902939c1de5..b510dc98bf1f 100644 --- a/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInTarget.java +++ b/platform/lang-impl/src/com/intellij/ide/impl/ProjectViewSelectInTarget.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,12 +55,13 @@ public abstract class ProjectViewSelectInTarget extends SelectInTargetPsiWrapper select(myProject, selector, getMinorViewId(), mySubId, virtualFile, requestFocus); } + @NotNull public static ActionCallback select(@NotNull Project project, - final Object toSelect, - @Nullable final String viewId, - @Nullable final String subviewId, - final VirtualFile virtualFile, - final boolean requestFocus) { + final Object toSelect, + @Nullable final String viewId, + @Nullable final String subviewId, + final VirtualFile virtualFile, + final boolean requestFocus) { final ActionCallback result = new ActionCallback(); @@ -86,7 +87,8 @@ public abstract class ProjectViewSelectInTarget extends SelectInTargetPsiWrapper if (requestFocus) { projectViewToolWindow.activate(runnable, false); - } else { + } + else { projectViewToolWindow.show(runnable); } @@ -96,7 +98,7 @@ public abstract class ProjectViewSelectInTarget extends SelectInTargetPsiWrapper @Override @NotNull - public Collection<SelectInTarget> getSubTargets(SelectInContext context) { + public Collection<SelectInTarget> getSubTargets(@NotNull SelectInContext context) { List<SelectInTarget> result = new ArrayList<SelectInTarget>(); AbstractProjectViewPane pane = ProjectView.getInstance(myProject).getProjectViewPaneById(getMinorViewId()); int index = 0; diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarIdeView.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarIdeView.java index 13ab984a7620..5a32f4d0531b 100644 --- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarIdeView.java +++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarIdeView.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import com.intellij.psi.*; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -48,6 +49,7 @@ public final class NavBarIdeView implements IdeView { myPanel.hideHint(); } + @NotNull @Override public PsiDirectory[] getDirectories() { final PsiDirectory dir = myPanel.getSelectedElement(PsiDirectory.class); diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/ProjectView.java b/platform/lang-impl/src/com/intellij/ide/projectView/ProjectView.java index cad0cf728c9a..d82a7c0a9b4b 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/ProjectView.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/ProjectView.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; @@ -34,14 +35,15 @@ public abstract class ProjectView { public abstract void select(Object element, VirtualFile file, boolean requestFocus); + @NotNull public abstract ActionCallback selectCB(Object element, VirtualFile file, boolean requestFocus); @Nullable public abstract PsiElement getParentOfCurrentSelection(); // show pane identified by id using default(or currently selected) subId - public abstract void changeView(String viewId); - public abstract void changeView(String viewId, String subId); + public abstract void changeView(@NotNull String viewId); + public abstract void changeView(@NotNull String viewId, String subId); public abstract void changeView(); @@ -55,19 +57,19 @@ public abstract class ProjectView { public abstract boolean isHideEmptyMiddlePackages(String paneId); - public abstract void setHideEmptyPackages(boolean hideEmptyPackages, String paneId); + public abstract void setHideEmptyPackages(boolean hideEmptyPackages, @NotNull String paneId); public abstract boolean isShowLibraryContents(String paneId); - public abstract void setShowLibraryContents(boolean showLibraryContents, String paneId); + public abstract void setShowLibraryContents(boolean showLibraryContents, @NotNull String paneId); public abstract boolean isShowModules(String paneId); - public abstract void setShowModules(boolean showModules, String paneId); + public abstract void setShowModules(boolean showModules, @NotNull String paneId); - public abstract void addProjectPane(final AbstractProjectViewPane pane); + public abstract void addProjectPane(@NotNull AbstractProjectViewPane pane); - public abstract void removeProjectPane(AbstractProjectViewPane instance); + public abstract void removeProjectPane(@NotNull AbstractProjectViewPane pane); public abstract AbstractProjectViewPane getProjectViewPaneById(String id); @@ -75,7 +77,7 @@ public abstract class ProjectView { public abstract boolean isAbbreviatePackageNames(String paneId); - public abstract void setAbbreviatePackageNames(boolean abbreviatePackageNames, String paneId); + public abstract void setAbbreviatePackageNames(boolean abbreviatePackageNames, @NotNull String paneId); /** * e.g. {@link com.intellij.ide.projectView.impl.ProjectViewPane#ID} @@ -86,11 +88,13 @@ public abstract class ProjectView { public abstract void selectPsiElement(PsiElement element, boolean requestFocus); public abstract boolean isSortByType(String paneId); - public abstract void setSortByType(String paneId, final boolean sortByType); + public abstract void setSortByType(@NotNull String paneId, final boolean sortByType); public abstract AbstractProjectViewPane getCurrentProjectViewPane(); + @NotNull public abstract Collection<String> getPaneIds(); + @NotNull public abstract Collection<SelectInTarget> getSelectInTargets(); } 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 d8bab8db9224..593d2576f370 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-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -156,6 +156,7 @@ public abstract class AbstractProjectViewPSIPane extends AbstractProjectViewPane CustomizationUtil.installPopupHandler(myTree, IdeActions.GROUP_PROJECT_VIEW_POPUP, ActionPlaces.PROJECT_VIEW_POPUP); } + @NotNull @Override public final ActionCallback updateFromRoot(boolean restoreExpandedPaths) { final ArrayList<Object> pathsToExpand = new ArrayList<Object>(); @@ -190,6 +191,7 @@ public abstract class AbstractProjectViewPSIPane extends AbstractProjectViewPane selectCB(element, file, requestFocus); } + @NotNull public ActionCallback selectCB(Object element, VirtualFile file, boolean requestFocus) { if (file != null) { return ((BaseProjectTreeBuilder)getTreeBuilder()).select(element, file, requestFocus); 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 c4708c48d19f..636824bd4896 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 @@ -204,9 +204,11 @@ public abstract class AbstractProjectViewPane implements DataProvider, Disposabl myTreeStructure = null; } + @NotNull public abstract ActionCallback updateFromRoot(boolean restoreExpandedPaths); public abstract void select(Object element, VirtualFile file, boolean requestFocus); + public void selectModule(final Module module, final boolean requestFocus) { doSelectModuleOrGroup(module, requestFocus); } @@ -482,6 +484,7 @@ public abstract class AbstractProjectViewPane implements DataProvider, Disposabl return myTree; } + @NotNull public PsiDirectory[] getSelectedDirectories() { List<PsiDirectory> directories = ContainerUtil.newArrayList(); for (PsiDirectoryNode node : getSelectedNodes(PsiDirectoryNode.class)) { @@ -541,6 +544,7 @@ public abstract class AbstractProjectViewPane implements DataProvider, Disposabl return PsiDirectory.EMPTY_ARRAY; } + @NotNull protected PsiDirectory[] getSelectedDirectoriesInAmbiguousCase(@NotNull final DefaultMutableTreeNode node) { final Object userObject = node.getUserObject(); if (userObject instanceof AbstractModuleNode) { diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/FavoritesViewToolWindowFactory.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/FavoritesViewToolWindowFactory.java index 17aa1b673f0c..451ae64b0bbb 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/FavoritesViewToolWindowFactory.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/FavoritesViewToolWindowFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,13 +24,14 @@ import com.intellij.openapi.wm.ToolWindowFactory; import com.intellij.openapi.wm.ex.ToolWindowEx; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; +import org.jetbrains.annotations.NotNull; /** * @author Konstantin Bulenkov */ public class FavoritesViewToolWindowFactory implements ToolWindowFactory, DumbAware { @Override - public void createToolWindowContent(Project project, ToolWindow toolWindow) { + public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) { if (toolWindow != null) { final ContentManager contentManager = toolWindow.getContentManager(); final FavoritesTreeViewPanel panel = new FavoritesPanel(project).getPanel(); 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 a8c7c0aa98a0..4172abdb1798 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 @@ -40,7 +40,10 @@ import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; -import com.intellij.openapi.components.*; +import com.intellij.openapi.components.PersistentStateComponent; +import com.intellij.openapi.components.State; +import com.intellij.openapi.components.Storage; +import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.Extensions; @@ -49,7 +52,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleUtil; +import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; @@ -70,13 +73,15 @@ import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.impl.content.ToolWindowContentUi; import com.intellij.psi.*; import com.intellij.psi.impl.file.PsiDirectoryFactory; -import com.intellij.psi.util.PsiUtilBase; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.AutoScrollFromSourceHandler; import com.intellij.ui.AutoScrollToSourceHandler; import com.intellij.ui.GuiUtils; import com.intellij.ui.components.JBList; -import com.intellij.ui.content.*; +import com.intellij.ui.content.Content; +import com.intellij.ui.content.ContentManager; +import com.intellij.ui.content.ContentManagerAdapter; +import com.intellij.ui.content.ContentManagerEvent; import com.intellij.ui.switcher.QuickActionProvider; import com.intellij.util.ArrayUtil; import com.intellij.util.IJSwingUtilities; @@ -114,7 +119,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo private final CopyPasteDelegator myCopyPasteDelegator; private boolean isInitialized; private boolean myExtensionsLoaded = false; - private final Project myProject; + @NotNull private final Project myProject; // + options private final Map<String, Boolean> myFlattenPackages = new THashMap<String, Boolean>(); @@ -134,7 +139,6 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo private final Map<String, Boolean> myAutoscrollToSource = new THashMap<String, Boolean>(); private final Map<String, Boolean> myAutoscrollFromSource = new THashMap<String, Boolean>(); private static final boolean ourAutoscrollFromSourceDefaults = false; - private static final boolean ourShowStructureDefaults = false; private String myCurrentViewId; private String myCurrentViewSubId; @@ -172,7 +176,6 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo @NonNls private static final String ELEMENT_AUTOSCROLL_TO_SOURCE = "autoscrollToSource"; @NonNls private static final String ELEMENT_AUTOSCROLL_FROM_SOURCE = "autoscrollFromSource"; @NonNls private static final String ELEMENT_SORT_BY_TYPE = "sortByType"; - @NonNls private static final String ELEMENT_FOLDERS_ALWAYS_ON_TOP = "foldersAlwaysOnTop"; private static final String ATTRIBUTE_ID = "id"; private JPanel myViewContentPanel; @@ -191,7 +194,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo private ContentManager myContentManager; private boolean myFoldersAlwaysOnTop = true; - public ProjectViewImpl(Project project, final FileEditorManager fileEditorManager, final ToolWindowManagerEx toolWindowManager) { + public ProjectViewImpl(@NotNull Project project, final FileEditorManager fileEditorManager, final ToolWindowManagerEx toolWindowManager) { myProject = project; constructUi(); @@ -221,16 +224,16 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } }; myAutoScrollToSourceHandler = new AutoScrollToSourceHandler() { - @Override - protected boolean isAutoScrollMode() { - return isAutoscrollToSource(myCurrentViewId); - } + @Override + protected boolean isAutoScrollMode() { + return isAutoscrollToSource(myCurrentViewId); + } - @Override - protected void setAutoScrollMode(boolean state) { - setAutoscrollToSource(state, myCurrentViewId); - } - }; + @Override + protected void setAutoScrollMode(boolean state) { + setAutoscrollToSource(state, myCurrentViewId); + } + }; toolWindowManager.addToolWindowManagerListener(new ToolWindowManagerAdapter(){ private boolean toolWindowVisible; @@ -268,16 +271,15 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } @Override + @NotNull public List<AnAction> getActions(boolean originalProvider) { ArrayList<AnAction> result = new ArrayList<AnAction>(); DefaultActionGroup views = new DefaultActionGroup("Change View", true); - boolean lastWasHeader = false; boolean lastHeaderHadKids = false; for (int i = 0; i < myContentManager.getContentCount(); i++) { Content each = myContentManager.getContent(i); if (each != null) { - if (each.getUserData(SUB_ID_KEY) == null) { if (lastHeaderHadKids) { views.add(new Separator()); @@ -291,12 +293,11 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } } } - } else { + } + else { lastHeaderHadKids = true; } - lastWasHeader = each.getUserData(SUB_ID_KEY) == null; - views.add(new ChangeViewAction(each.getUserData(ID_KEY), each.getUserData(SUB_ID_KEY))); } } @@ -304,13 +305,14 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo result.add(new Separator()); - ArrayList<AnAction> secondary = new ArrayList<AnAction>(); + List<AnAction> secondary = new ArrayList<AnAction>(); if (myActionGroup != null) { AnAction[] kids = myActionGroup.getChildren(null); for (AnAction each : kids) { if (myActionGroup.isPrimary(each)) { result.add(each); - } else { + } + else { secondary.add(each); } } @@ -325,7 +327,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo private final String myId; private final String mySubId; - private ChangeViewAction(String id, String subId) { + private ChangeViewAction(@NotNull String id, String subId) { myId = id; mySubId = subId; } @@ -348,7 +350,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } @Override - public synchronized void addProjectPane(final AbstractProjectViewPane pane) { + public synchronized void addProjectPane(@NotNull final AbstractProjectViewPane pane) { myUninitializedPanes.add(pane); SelectInTarget selectInTarget = pane.createSelectInTarget(); if (selectInTarget != null) { @@ -360,7 +362,8 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } @Override - public synchronized void removeProjectPane(AbstractProjectViewPane pane) { + public synchronized void removeProjectPane(@NotNull AbstractProjectViewPane pane) { + ApplicationManager.getApplication().assertIsDispatchThread(); myUninitializedPanes.remove(pane); //assume we are completely initialized here String idToRemove = pane.getId(); @@ -425,7 +428,8 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo myUninitializedPanes.clear(); } - private void doAddPane(final AbstractProjectViewPane newPane) { + private void doAddPane(@NotNull final AbstractProjectViewPane newPane) { + ApplicationManager.getApplication().assertIsDispatchThread(); int index; final ContentManager manager = myContentManager; for (index = 0; index < manager.getContentCount(); index++) { @@ -473,7 +477,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo Disposer.register(this, newPane); } - private void showPane(AbstractProjectViewPane newPane) { + private void showPane(@NotNull AbstractProjectViewPane newPane) { AbstractProjectViewPane currentPane = getCurrentProjectViewPane(); PsiElement selectedPsiElement = null; if (currentPane != null) { @@ -550,30 +554,26 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo myActionGroup.remove(collapseAction); } } - ((ToolWindowEx)window).setTitleActions(new AnAction[] {scrollAction, collapseAction}); + ((ToolWindowEx)window).setTitleActions(scrollAction, collapseAction); } // public for tests - public synchronized void setupImpl(final ToolWindow toolWindow) { + public synchronized void setupImpl(@NotNull ToolWindow toolWindow) { setupImpl(toolWindow, true); } // public for tests - public synchronized void setupImpl(final ToolWindow toolWindow, final boolean loadPaneExtensions) { + public synchronized void setupImpl(@NotNull ToolWindow toolWindow, final boolean loadPaneExtensions) { + ApplicationManager.getApplication().assertIsDispatchThread(); myActionGroup = new DefaultActionGroup(); myAutoScrollFromSourceHandler.install(); - if (toolWindow != null) { - myContentManager = toolWindow.getContentManager(); - if (!ApplicationManager.getApplication().isUnitTestMode()) { - toolWindow.setContentUiType(ToolWindowContentUiType.COMBO, null); - ((ToolWindowEx)toolWindow).setAdditionalGearActions(myActionGroup); - toolWindow.getComponent().putClientProperty(ToolWindowContentUi.HIDE_ID_LABEL, "true"); - } - } else { - final ContentFactory contentFactory = ServiceManager.getService(ContentFactory.class); - myContentManager = contentFactory.createContentManager(false, myProject); + myContentManager = toolWindow.getContentManager(); + if (!ApplicationManager.getApplication().isUnitTestMode()) { + toolWindow.setContentUiType(ToolWindowContentUiType.COMBO, null); + ((ToolWindowEx)toolWindow).setAdditionalGearActions(myActionGroup); + toolWindow.getComponent().putClientProperty(ToolWindowContentUi.HIDE_ID_LABEL, "true"); } GuiUtils.replaceJSplitPaneWithIDEASplitter(myPanel); @@ -655,11 +655,11 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } class FlattenPackagesDependableAction extends PaneOptionAction { - FlattenPackagesDependableAction(Map<String, Boolean> optionsMap, - final String text, - final String description, - final Icon icon, - boolean optionDefaultValue) { + FlattenPackagesDependableAction(@NotNull Map<String, Boolean> optionsMap, + @NotNull String text, + @NotNull String description, + @NotNull Icon icon, + boolean optionDefaultValue) { super(optionsMap, text, description, icon, optionDefaultValue); } @@ -782,15 +782,15 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } } + @NotNull @Override public ActionCallback selectCB(Object element, VirtualFile file, boolean requestFocus) { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane != null && viewPane instanceof AbstractProjectViewPSIPane) { - return ((AbstractProjectViewPSIPane) viewPane).selectCB(element, file, requestFocus); - } else { - select(element, file, requestFocus); - return new ActionCallback.Done(); + return ((AbstractProjectViewPSIPane)viewPane).selectCB(element, file, requestFocus); } + select(element, file, requestFocus); + return new ActionCallback.Done(); } @Override @@ -844,10 +844,10 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo private final Map<String, Boolean> myOptionsMap; private final boolean myOptionDefaultValue; - PaneOptionAction(Map<String, Boolean> optionsMap, - final String text, - final String description, - final Icon icon, + PaneOptionAction(@NotNull Map<String, Boolean> optionsMap, + @NotNull String text, + @NotNull String description, + Icon icon, boolean optionDefaultValue) { super(text, description, icon); myOptionsMap = optionsMap; @@ -946,6 +946,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } } + @NotNull private PsiElement[] getElementsToDelete() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); PsiElement[] elements = viewPane.getSelectedPSIElements(); @@ -1038,7 +1039,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo if (virtualFiles == null || virtualFiles.length <= 1) return null; final Set<Module> modules = new HashSet<Module>(); for (VirtualFile virtualFile : virtualFiles) { - modules.add(ModuleUtil.findModuleForFile(virtualFile, myProject)); + modules.add(ModuleUtilCore.findModuleForFile(virtualFile, myProject)); } return modules.size() == 1 ? modules.iterator().next() : null; } @@ -1157,7 +1158,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo return null; } - private void detachLibrary(final LibraryOrderEntry orderEntry, final Project project) { + private void detachLibrary(@NotNull final LibraryOrderEntry orderEntry, @NotNull Project project) { final Module module = orderEntry.getOwnerModule(); String message = IdeBundle.message("detach.library.from.module", orderEntry.getPresentableName(), module.getName()); String title = IdeBundle.message("detach.library"); @@ -1230,7 +1231,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo * otherwise VirtualFileArrayRule will return all module's content roots when just one of them is selected */ @Nullable - private Module moduleBySingleContentRoot(VirtualFile file) { + private Module moduleBySingleContentRoot(@NotNull VirtualFile file) { if (ProjectRootsUtil.isModuleContentRoot(file, myProject)) { Module module = ProjectRootManager.getInstance(myProject).getFileIndex().getModuleForFile(file); if (module != null && !module.isDisposed() && ModuleRootManager.getInstance(module).getContentRoots().length == 1) { @@ -1241,8 +1242,9 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo return null; } - private <T> List<T> getSelectedElements(Class<T> klass) { - ArrayList<T> result = new ArrayList<T>(); + @NotNull + private <T> List<T> getSelectedElements(@NotNull Class<T> klass) { + List<T> result = new ArrayList<T>(); final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); if (viewPane == null) return result; final Object[] elements = viewPane.getSelectedElements(); @@ -1276,6 +1278,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } } + @NotNull @Override public PsiDirectory[] getDirectories() { final AbstractProjectViewPane viewPane = getCurrentProjectViewPane(); @@ -1295,12 +1298,12 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo @Override public void selectPsiElement(PsiElement element, boolean requestFocus) { if (element == null) return; - VirtualFile virtualFile = PsiUtilBase.getVirtualFile(element); + VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element); select(element, virtualFile, requestFocus); } - private static void readOption(Element node, Map<String, Boolean> options) { + private static void readOption(Element node, @NotNull Map<String, Boolean> options) { if (node == null) return; List attributes = node.getAttributes(); for (final Object attribute1 : attributes) { @@ -1309,7 +1312,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } } - private static void writeOption(Element parentNode, Map<String, Boolean> optionsForPanes, String optionName) { + private static void writeOption(@NotNull Element parentNode, @NotNull Map<String, Boolean> optionsForPanes, @NotNull String optionName) { Element e = new Element(optionName); for (Map.Entry<String, Boolean> entry : optionsForPanes.entrySet()) { final String key = entry.getKey(); @@ -1354,7 +1357,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } } - private void readPaneState(Element panesElement) { + private void readPaneState(@NotNull Element panesElement) { @SuppressWarnings({"unchecked"}) final List<Element> paneElements = panesElement.getChildren(ELEMENT_PANE); @@ -1412,7 +1415,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo return parentNode; } - private void writePaneState(Element panesElement) { + private void writePaneState(@NotNull Element panesElement) { for (AbstractProjectViewPane pane : myId2Pane.values()) { Element paneElement = new Element(ELEMENT_PANE); paneElement.setAttribute(ATTRIBUTE_ID, pane.getId()); @@ -1425,7 +1428,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo panesElement.addContent(paneElement); } for (Element element : myUninitializedPaneState.values()) { - panesElement.addContent((Element) element.clone()); + panesElement.addContent(element.clone()); } } @@ -1496,10 +1499,11 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } @Override - public void setShowLibraryContents(boolean showLibraryContents, String paneId) { + public void setShowLibraryContents(boolean showLibraryContents, @NotNull String paneId) { setPaneOption(myShowLibraryContents, showLibraryContents, paneId, true); } + @NotNull public ActionCallback setShowLibraryContentsCB(boolean showLibraryContents, String paneId) { return setPaneOption(myShowLibraryContents, showLibraryContents, paneId, true); } @@ -1510,21 +1514,22 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } @Override - public void setShowModules(boolean showModules, String paneId) { + public void setShowModules(boolean showModules, @NotNull String paneId) { setPaneOption(myShowModules, showModules, paneId, true); } @Override - public void setHideEmptyPackages(boolean hideEmptyPackages, String paneId) { + public void setHideEmptyPackages(boolean hideEmptyPackages, @NotNull String paneId) { setPaneOption(myHideEmptyPackages, hideEmptyPackages, paneId, true); } @Override - public void setAbbreviatePackageNames(boolean abbreviatePackageNames, String paneId) { + public void setAbbreviatePackageNames(boolean abbreviatePackageNames, @NotNull String paneId) { setPaneOption(myAbbreviatePackageNames, abbreviatePackageNames, paneId, true); } - private ActionCallback setPaneOption(Map<String, Boolean> optionsMap, boolean value, String paneId, final boolean updatePane) { + @NotNull + private ActionCallback setPaneOption(@NotNull Map<String, Boolean> optionsMap, boolean value, String paneId, final boolean updatePane) { optionsMap.put(paneId, value ? Boolean.TRUE : Boolean.FALSE); if (updatePane) { final AbstractProjectViewPane pane = getProjectViewPaneById(paneId); @@ -1535,7 +1540,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo return new ActionCallback.Done(); } - private static boolean getPaneOptionValue(Map<String, Boolean> optionsMap, String paneId, boolean defaultValue) { + private static boolean getPaneOptionValue(@NotNull Map<String, Boolean> optionsMap, String paneId, boolean defaultValue) { final Boolean value = optionsMap.get(paneId); return value == null ? defaultValue : value.booleanValue(); } @@ -1573,7 +1578,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo private static class SelectionInfo { private final Object[] myElements; - private SelectionInfo(Object[] elements) { + private SelectionInfo(@NotNull Object[] elements) { myElements = elements; } @@ -1600,6 +1605,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } } + @NotNull public static SelectionInfo create(final AbstractProjectViewPane viewPane) { List<Object> selectedElements = Collections.emptyList(); if (viewPane != null) { @@ -1621,7 +1627,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo private class MyAutoScrollFromSourceHandler extends AutoScrollFromSourceHandler { private MyAutoScrollFromSourceHandler() { - super(ProjectViewImpl.this.myProject,ProjectViewImpl.this.myViewContentPanel, ProjectViewImpl.this); + super(ProjectViewImpl.this.myProject, myViewContentPanel, ProjectViewImpl.this); } @Override @@ -1631,7 +1637,8 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo if (fileEditor instanceof TextEditor) { Editor editor = ((TextEditor)fileEditor).getEditor(); selectElementAtCaretNotLosingFocus(editor); - } else { + } + else { final VirtualFile file = FileEditorManagerEx.getInstanceEx(myProject).getFile(fileEditor); if (file != null) { final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file); @@ -1679,19 +1686,19 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } } - private void selectElementAtCaretNotLosingFocus(final Editor editor) { + private void selectElementAtCaretNotLosingFocus(@NotNull Editor editor) { if (IJSwingUtilities.hasFocus(getCurrentProjectViewPane().getComponentToFocus())) return; selectElementAtCaret(editor); } - private void selectElementAtCaret(Editor editor) { + private void selectElementAtCaret(@NotNull Editor editor) { final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument()); if (file == null) return; scrollFromFile(file, editor); } - private void scrollFromFile(PsiFile file, @Nullable Editor editor) { + private void scrollFromFile(@NotNull PsiFile file, @Nullable Editor editor) { final MySelectInContext selectInContext = new MySelectInContext(file, editor); final SelectInTarget target = mySelectInTargets.get(getCurrentViewId()); @@ -1719,10 +1726,10 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } private class MySelectInContext implements SelectInContext { - private final PsiFile myPsiFile; + @NotNull private final PsiFile myPsiFile; @Nullable private final Editor myEditor; - private MySelectInContext(final PsiFile psiFile, @Nullable Editor editor) { + private MySelectInContext(@NotNull PsiFile psiFile, @Nullable Editor editor) { myPsiFile = psiFile; myEditor = editor; } @@ -1733,13 +1740,14 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo return myProject; } + @NotNull private PsiFile getPsiFile() { return myPsiFile; } @Override + @NotNull public FileEditorProvider getFileEditorProvider() { - if (myPsiFile == null) return null; return new FileEditorProvider() { @Override public FileEditor openFileEditor() { @@ -1748,6 +1756,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo }; } + @NotNull private PsiElement getPsiElement() { PsiElement e = null; if (myEditor != null) { @@ -1780,7 +1789,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } @Override - public void setSortByType(String paneId, final boolean sortByType) { + public void setSortByType(@NotNull String paneId, final boolean sortByType) { setPaneOption(mySortByType, sortByType, paneId, false); final AbstractProjectViewPane pane = getProjectViewPaneById(paneId); pane.installComparator(); @@ -1788,8 +1797,7 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo private class SortByTypeAction extends ToggleAction { private SortByTypeAction() { - super(IdeBundle.message("action.sort.by.type"), IdeBundle.message("action.sort.by.type"), - AllIcons.ObjectBrowser.SortByType); + super(IdeBundle.message("action.sort.by.type"), IdeBundle.message("action.sort.by.type"), AllIcons.ObjectBrowser.SortByType); } @Override @@ -1845,11 +1853,13 @@ public class ProjectViewImpl extends ProjectView implements PersistentStateCompo } } + @NotNull @Override public Collection<String> getPaneIds() { return myId2Pane.keySet(); } + @NotNull @Override public Collection<SelectInTarget> getSelectInTargets() { ensurePanesLoaded(); diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewToolWindowFactory.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewToolWindowFactory.java index 192f5966c489..f4b3803a63d0 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewToolWindowFactory.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewToolWindowFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,13 +23,14 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowFactoryEx; +import org.jetbrains.annotations.NotNull; /** * @author yole */ public class ProjectViewToolWindowFactory implements ToolWindowFactoryEx, DumbAware { @Override - public void createToolWindowContent(Project project, ToolWindow toolWindow) { + public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) { ((ProjectViewImpl) ProjectView.getInstance(project)).setupImpl(toolWindow); } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ShowModulesAction.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ShowModulesAction.java index 6e53e96725b5..370b7a335bf4 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ShowModulesAction.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ShowModulesAction.java @@ -24,6 +24,7 @@ import com.intellij.openapi.actionSystem.ToggleAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.util.PlatformUtils; +import org.jetbrains.annotations.NotNull; /** * @author anna @@ -43,6 +44,7 @@ public abstract class ShowModulesAction extends ToggleAction { return ProjectView.getInstance(myProject).isShowModules(getId()); } + @NotNull protected abstract String getId(); @Override diff --git a/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java b/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java index 2fbbdc7ea348..9daf15441dbf 100644 --- a/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -252,7 +252,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { public void selectScope(final NamedScope scope) { refreshScope(scope); - if (scope != DefaultScopesProvider.getAllScope() && scope != null) { + if (scope != CustomScopesProviderEx.getAllScope() && scope != null) { CURRENT_SCOPE_NAME = scope.getName(); } } @@ -323,7 +323,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { public void refreshScope(@Nullable NamedScope scope) { FileTreeModelBuilder.clearCaches(myProject); if (scope == null) { //was deleted - scope = DefaultScopesProvider.getAllScope(); + scope = CustomScopesProviderEx.getAllScope(); } LOG.assertTrue(scope != null); final NamedScopesHolder holder = NamedScopesHolder.getHolder(myProject, scope.getName(), myDependencyValidationManager); @@ -364,7 +364,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { protected NamedScope getCurrentScope() { NamedScope scope = NamedScopesHolder.getScope(myProject, CURRENT_SCOPE_NAME); if (scope == null) { - scope = DefaultScopesProvider.getAllScope(); + scope = CustomScopesProviderEx.getAllScope(); } LOG.assertTrue(scope != null); return scope; @@ -888,6 +888,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { return null; } + @NotNull @Override public PsiDirectory[] getDirectories() { PsiDirectory directory = getDirectory(); 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 5c929e99b736..dc47793401e0 100644 --- a/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeViewPane.java +++ b/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeViewPane.java @@ -162,6 +162,7 @@ public class ScopeViewPane extends AbstractProjectViewPane { public void addToolbarActions(DefaultActionGroup actionGroup) { actionGroup.add(ActionManager.getInstance().getAction("ScopeView.EditScopes")); actionGroup.addAction(new ShowModulesAction(myProject){ + @NotNull @Override protected String getId() { return ScopeViewPane.this.getId(); @@ -169,6 +170,7 @@ public class ScopeViewPane extends AbstractProjectViewPane { }).setAsSecondary(true); } + @NotNull @Override public ActionCallback updateFromRoot(boolean restoreExpandedPaths) { saveExpandedPaths(); @@ -249,14 +251,13 @@ public class ScopeViewPane extends AbstractProjectViewPane { if (data != null) { return data; } - return myViewPanel != null ? myViewPanel.getData(dataId) : null; + return myViewPanel == null ? null : myViewPanel.getData(dataId); } @NotNull @Override public ActionCallback getReady(@NotNull Object requestor) { final ActionCallback callback = myViewPanel.getActionCallback(); - return myViewPanel == null ? new ActionCallback.Rejected() : - callback != null ? callback : new ActionCallback.Done(); + return callback == null ? new ActionCallback.Done() : callback; } } diff --git a/platform/lang-impl/src/com/intellij/ide/structureView/impl/StructureViewToolWindowFactory.java b/platform/lang-impl/src/com/intellij/ide/structureView/impl/StructureViewToolWindowFactory.java index b05193bf858a..c06cd2cb5d59 100644 --- a/platform/lang-impl/src/com/intellij/ide/structureView/impl/StructureViewToolWindowFactory.java +++ b/platform/lang-impl/src/com/intellij/ide/structureView/impl/StructureViewToolWindowFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,13 +22,14 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowFactory; import com.intellij.openapi.wm.ex.ToolWindowEx; +import org.jetbrains.annotations.NotNull; /** * @author yole */ public class StructureViewToolWindowFactory implements ToolWindowFactory, DumbAware { @Override - public void createToolWindowContent(Project project, ToolWindow toolWindow) { + public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) { StructureViewFactoryImpl factory = (StructureViewFactoryImpl)StructureViewFactory.getInstance(project); factory.initToolWindow((ToolWindowEx)toolWindow); } diff --git a/platform/lang-impl/src/com/intellij/ide/todo/TodoToolWindowFactory.java b/platform/lang-impl/src/com/intellij/ide/todo/TodoToolWindowFactory.java index ad5368672fec..4217f5ace393 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/TodoToolWindowFactory.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/TodoToolWindowFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,14 @@ import com.intellij.openapi.wm.ToolWindowFactory; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.project.Project; import com.intellij.openapi.components.ServiceManager; +import org.jetbrains.annotations.NotNull; /** * @author yole */ public class TodoToolWindowFactory implements ToolWindowFactory { @Override - public void createToolWindowContent(Project project, ToolWindow toolWindow) { + public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) { TodoView todoView = ServiceManager.getService(project, TodoView.class); todoView.initToolWindow(toolWindow); } diff --git a/platform/lang-impl/src/com/intellij/ide/util/MemberChooser.java b/platform/lang-impl/src/com/intellij/ide/util/MemberChooser.java index 80099b35c3d8..54ae97d446b5 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/MemberChooser.java +++ b/platform/lang-impl/src/com/intellij/ide/util/MemberChooser.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,6 @@ import javax.swing.event.TreeSelectionListener; import javax.swing.tree.*; import java.awt.*; import java.awt.event.*; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; import java.util.*; import java.util.List; @@ -536,9 +534,9 @@ public class MemberChooser<T extends ClassMember> extends DialogWrapper implemen protected void doSort() { Pair<ElementNode, List<ElementNode>> pair = storeSelection(); - Enumeration<ParentNode> children = getRootNodeChildren(); + Enumeration<TreeNode> children = getRootNodeChildren(); while (children.hasMoreElements()) { - ParentNode classNode = children.nextElement(); + ParentNode classNode = (ParentNode)children.nextElement(); sortNode(classNode, myComparator); myTreeModel.nodeStructureChanged(classNode); } @@ -547,10 +545,10 @@ public class MemberChooser<T extends ClassMember> extends DialogWrapper implemen } private static void sortNode(ParentNode node, final Comparator<ElementNode> sortComparator) { - ArrayList<MemberNode> arrayList = new ArrayList<MemberNode>(); - Enumeration<MemberNode> children = node.children(); + ArrayList<ElementNode> arrayList = new ArrayList<ElementNode>(); + Enumeration<TreeNode> children = node.children(); while (children.hasMoreElements()) { - arrayList.add(children.nextElement()); + arrayList.add((ElementNode)children.nextElement()); } Collections.sort(arrayList, sortComparator); @@ -571,16 +569,16 @@ public class MemberChooser<T extends ClassMember> extends DialogWrapper implemen DefaultMutableTreeNode root = getRootNode(); if (!myShowClasses || myContainerNodes.isEmpty()) { List<ParentNode> otherObjects = new ArrayList<ParentNode>(); - Enumeration<ParentNode> children = getRootNodeChildren(); + Enumeration<TreeNode> children = getRootNodeChildren(); ParentNode newRoot = new ParentNode(null, new MemberChooserObjectBase(getAllContainersNodeName()), new Ref<Integer>(0)); while (children.hasMoreElements()) { - final ParentNode nextElement = children.nextElement(); + final ParentNode nextElement = (ParentNode)children.nextElement(); if (nextElement instanceof ContainerNode) { final ContainerNode containerNode = (ContainerNode)nextElement; - Enumeration<MemberNode> memberNodes = containerNode.children(); + Enumeration<TreeNode> memberNodes = containerNode.children(); List<MemberNode> memberNodesList = new ArrayList<MemberNode>(); while (memberNodes.hasMoreElements()) { - memberNodesList.add(memberNodes.nextElement()); + memberNodesList.add((MemberNode)memberNodes.nextElement()); } for (MemberNode memberNode : memberNodesList) { newRoot.add(memberNode); @@ -595,13 +593,13 @@ public class MemberChooser<T extends ClassMember> extends DialogWrapper implemen if (newRoot.children().hasMoreElements()) root.add(newRoot); } else { - Enumeration<ParentNode> children = getRootNodeChildren(); + Enumeration<TreeNode> children = getRootNodeChildren(); while (children.hasMoreElements()) { - ParentNode allClassesNode = children.nextElement(); - Enumeration<MemberNode> memberNodes = allClassesNode.children(); + ParentNode allClassesNode = (ParentNode)children.nextElement(); + Enumeration<TreeNode> memberNodes = allClassesNode.children(); ArrayList<MemberNode> arrayList = new ArrayList<MemberNode>(); while (memberNodes.hasMoreElements()) { - arrayList.add(memberNodes.nextElement()); + arrayList.add((MemberNode)memberNodes.nextElement()); } Collections.sort(arrayList, myComparator); for (MemberNode memberNode : arrayList) { @@ -626,7 +624,7 @@ public class MemberChooser<T extends ClassMember> extends DialogWrapper implemen return IdeBundle.message("node.memberchooser.all.classes"); } - private Enumeration<ParentNode> getRootNodeChildren() { + private Enumeration<TreeNode> getRootNodeChildren() { return getRootNode().children(); } diff --git a/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java b/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java index ccf63a429346..267333399dbd 100644 --- a/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java +++ b/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java @@ -933,7 +933,8 @@ public class GeneratedParserUtilBase { for (Pair<PsiBuilder.Marker, Integer> pair : siblingList) { if (pair.second != rating || parenPair != null && pair.first == parenPair.second) break main; if (++count >= MAX_CHILDREN_IN_TREE) { - final PsiBuilder.Marker parentMarker = pair.first.precede(); + PsiBuilder.Marker parentMarker = pair.first.precede(); + parentMarker.setCustomEdgeTokenBinders(WhitespacesBinders.GREEDY_LEFT_BINDER, null); while (count-- > 0) { siblingList.removeFirst(); } @@ -986,6 +987,7 @@ public class GeneratedParserUtilBase { else { if (marker == null) { marker = builder_.mark(); + marker.setCustomEdgeTokenBinders(WhitespacesBinders.GREEDY_LEFT_BINDER, null); } final boolean result = (!parenList.isEmpty() || eatMoreCondition.parse(builder_, level + 1)) && parser.parse(builder_, level + 1); if (result) { diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/actions/SelectWordAtCaretAction.java b/platform/lang-impl/src/com/intellij/openapi/editor/actions/SelectWordAtCaretAction.java index b70189f5140a..0cf8e9e984d0 100644 --- a/platform/lang-impl/src/com/intellij/openapi/editor/actions/SelectWordAtCaretAction.java +++ b/platform/lang-impl/src/com/intellij/openapi/editor/actions/SelectWordAtCaretAction.java @@ -35,6 +35,7 @@ import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.text.CharArrayUtil; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; @@ -45,18 +46,13 @@ public class SelectWordAtCaretAction extends TextComponentEditorAction implement setInjectedContext(true); } - @Override - public EditorActionHandler getHandler() { - return new Handler(super.getHandler()); - } - private static class DefaultHandler extends EditorActionHandler { private DefaultHandler() { super(true); } @Override - public void execute(Editor editor, DataContext dataContext) { + public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) { int lineNumber = editor.getCaretModel().getLogicalPosition().line; int caretOffset = editor.getCaretModel().getOffset(); Document document = editor.getDocument(); @@ -94,23 +90,24 @@ public class SelectWordAtCaretAction extends TextComponentEditorAction implement } } - private static class Handler extends EditorActionHandler { + public static class Handler extends EditorActionHandler { private final EditorActionHandler myDefaultHandler; - private Handler(EditorActionHandler defaultHandler) { + public Handler(EditorActionHandler defaultHandler) { super(true); myDefaultHandler = defaultHandler; + } @Override - public void execute(Editor editor, DataContext dataContext) { + public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) { final IndentGuideDescriptor guide = editor.getIndentsModel().getCaretIndentGuide(); final SelectionModel selectionModel = editor.getSelectionModel(); if (guide != null && !selectionModel.hasSelection() && !selectionModel.hasBlockSelection() && isWhitespaceAtCaret(editor)) { selectWithGuide(editor, guide); } else { - myDefaultHandler.execute(editor, dataContext); + myDefaultHandler.execute(editor, caret, dataContext); } } diff --git a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorPsiDataProvider.java b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorPsiDataProvider.java index 1f911936637a..7400e982b5a0 100644 --- a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorPsiDataProvider.java +++ b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/text/TextEditorPsiDataProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,12 @@ package com.intellij.openapi.fileEditor.impl.text; import com.intellij.codeInsight.TargetElementUtilBase; import com.intellij.ide.IdeView; import com.intellij.ide.util.EditorHelper; +import com.intellij.injected.editor.EditorWindow; +import com.intellij.injected.editor.InjectedCaret; import com.intellij.lang.Language; +import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.SelectionModel; +import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.fileEditor.EditorDataProvider; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; @@ -42,45 +45,64 @@ import static com.intellij.util.containers.ContainerUtil.addIfNotNull; public class TextEditorPsiDataProvider implements EditorDataProvider { @Override @Nullable - public Object getData(@NotNull final String dataId, @NotNull final Editor e, @NotNull final VirtualFile file) { - if (!file.isValid()) return null; + public Object getData(@NotNull final String dataId, @NotNull final Editor e, @NotNull final Caret caret) { + if (!(e instanceof EditorEx)) { + return null; + } + VirtualFile file = ((EditorEx)e).getVirtualFile(); + if (file == null || !file.isValid()) return null; + Project project = e.getProject(); if (dataId.equals(injectedId(EDITOR.getName()))) { - if (PsiDocumentManager.getInstance(e.getProject()).isUncommited(e.getDocument())) { + if (project == null || PsiDocumentManager.getInstance(project).isUncommited(e.getDocument())) { return e; } else { - return InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(e, getPsiFile(e, file)); + return InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(e, caret, getPsiFile(e, file)); } } + if (HOST_EDITOR.is(dataId)) { + return e instanceof EditorWindow ? ((EditorWindow)e).getDelegate() : e; + } + if (CARET.is(dataId)) { + return caret; + } + if (dataId.equals(injectedId(CARET.getName()))) { + Editor editor = (Editor)getData(injectedId(EDITOR.getName()), e, caret); + assert editor != null; + return getInjectedCaret(editor, caret); + } if (dataId.equals(injectedId(PSI_ELEMENT.getName()))) { - return getPsiElementIn((Editor)getData(injectedId(EDITOR.getName()), e, file), file); + Editor editor = (Editor)getData(injectedId(EDITOR.getName()), e, caret); + assert editor != null; + Caret injectedCaret = getInjectedCaret(editor, caret); + return getPsiElementIn(editor, injectedCaret, file); } if (PSI_ELEMENT.is(dataId)){ - return getPsiElementIn(e, file); + return getPsiElementIn(e, caret, file); } if (dataId.equals(injectedId(LANGUAGE.getName()))) { - PsiFile psiFile = (PsiFile)getData(injectedId(PSI_FILE.getName()), e, file); - Editor editor = (Editor)getData(injectedId(EDITOR.getName()), e, file); + PsiFile psiFile = (PsiFile)getData(injectedId(PSI_FILE.getName()), e, caret); + Editor editor = (Editor)getData(injectedId(EDITOR.getName()), e, caret); if (psiFile == null || editor == null) return null; - return getLanguageAtCurrentPositionInEditor(editor, psiFile); + Caret injectedCaret = getInjectedCaret(editor, caret); + return getLanguageAtCurrentPositionInEditor(injectedCaret, psiFile); } if (LANGUAGE.is(dataId)) { final PsiFile psiFile = getPsiFile(e, file); if (psiFile == null) return null; - return getLanguageAtCurrentPositionInEditor(e, psiFile); + return getLanguageAtCurrentPositionInEditor(caret, psiFile); } if (dataId.equals(injectedId(VIRTUAL_FILE.getName()))) { - PsiFile psiFile = (PsiFile)getData(injectedId(PSI_FILE.getName()), e, file); + PsiFile psiFile = (PsiFile)getData(injectedId(PSI_FILE.getName()), e, caret); if (psiFile == null) return null; return psiFile.getVirtualFile(); } if (dataId.equals(injectedId(PSI_FILE.getName()))) { - Editor editor = (Editor)getData(injectedId(EDITOR.getName()), e, file); + Editor editor = (Editor)getData(injectedId(EDITOR.getName()), e, caret); if (editor == null) { return null; } - final Project project = editor.getProject(); if (project == null) { return null; } @@ -90,7 +112,7 @@ public class TextEditorPsiDataProvider implements EditorDataProvider { return getPsiFile(e, file); } if (IDE_VIEW.is(dataId)) { - final PsiFile psiFile = PsiManager.getInstance(e.getProject()).findFile(file); + final PsiFile psiFile = project == null ? null : PsiManager.getInstance(project).findFile(file); final PsiDirectory psiDirectory = psiFile != null ? psiFile.getParent() : null; if (psiDirectory != null && psiDirectory.isPhysical()) { return new IdeView() { @@ -103,6 +125,7 @@ public class TextEditorPsiDataProvider implements EditorDataProvider { } } + @NotNull @Override public PsiDirectory[] getDirectories() { return new PsiDirectory[]{psiDirectory}; @@ -116,20 +139,32 @@ public class TextEditorPsiDataProvider implements EditorDataProvider { } } if (CONTEXT_LANGUAGES.is(dataId)) { - return computeLanguages(e, file); + return computeLanguages(e, caret); } return null; } - private static Language getLanguageAtCurrentPositionInEditor(final Editor editor, final PsiFile psiFile) { - final SelectionModel selectionModel = editor.getSelectionModel(); - int caretOffset = editor.getCaretModel().getOffset(); - int mostProbablyCorrectLanguageOffset = caretOffset == selectionModel.getSelectionStart() || - caretOffset == selectionModel.getSelectionEnd() - ? selectionModel.getSelectionStart() + @NotNull + private static Caret getInjectedCaret(@NotNull Editor editor, @NotNull Caret hostCaret) { + if (!(editor instanceof EditorWindow) || hostCaret instanceof InjectedCaret) { + return hostCaret; + } + for (Caret caret : editor.getCaretModel().getAllCarets()) { + if (((InjectedCaret)caret).getDelegate() == hostCaret) { + return caret; + } + } + throw new IllegalArgumentException("Cannot find injected caret corresponding to " + hostCaret); + } + + private static Language getLanguageAtCurrentPositionInEditor(Caret caret, final PsiFile psiFile) { + int caretOffset = caret.getOffset(); + int mostProbablyCorrectLanguageOffset = caretOffset == caret.getSelectionStart() || + caretOffset == caret.getSelectionEnd() + ? caret.getSelectionStart() : caretOffset; - if (selectionModel.hasSelection()) { - return getLanguageAtOffset(psiFile, mostProbablyCorrectLanguageOffset, selectionModel.getSelectionEnd()); + if (caret.hasSelection()) { + return getLanguageAtOffset(psiFile, mostProbablyCorrectLanguageOffset, caret.getSelectionEnd()); } return PsiUtilCore.getLanguageAtOffset(psiFile, mostProbablyCorrectLanguageOffset); @@ -148,12 +183,13 @@ public class TextEditorPsiDataProvider implements EditorDataProvider { } @Nullable - private static PsiElement getPsiElementIn(@NotNull Editor editor, @NotNull VirtualFile file) { + private static PsiElement getPsiElementIn(@NotNull Editor editor, @NotNull Caret caret, @NotNull VirtualFile file) { final PsiFile psiFile = getPsiFile(editor, file); if (psiFile == null) return null; try { - return TargetElementUtilBase.findTargetElement(editor, TargetElementUtilBase.getInstance().getReferenceSearchFlags()); + TargetElementUtilBase util = TargetElementUtilBase.getInstance(); + return util.findTargetElement(editor, util.getReferenceSearchFlags(), caret.getOffset()); } catch (IndexNotReadyException e) { return null; @@ -173,13 +209,13 @@ public class TextEditorPsiDataProvider implements EditorDataProvider { return psiFile != null && psiFile.isValid() ? psiFile : null; } - private Language[] computeLanguages(@NotNull Editor editor, @NotNull VirtualFile file) { + private Language[] computeLanguages(@NotNull Editor editor, @NotNull Caret caret) { LinkedHashSet<Language> set = new LinkedHashSet<Language>(4); - Language injectedLanguage = (Language)getData(injectedId(LANGUAGE.getName()), editor, file); + Language injectedLanguage = (Language)getData(injectedId(LANGUAGE.getName()), editor, caret); addIfNotNull(injectedLanguage, set); - Language language = (Language)getData(LANGUAGE.getName(), editor, file); + Language language = (Language)getData(LANGUAGE.getName(), editor, caret); addIfNotNull(language, set); - PsiFile psiFile = (PsiFile)getData(PSI_FILE.getName(), editor, file); + PsiFile psiFile = (PsiFile)getData(PSI_FILE.getName(), editor, caret); if (psiFile != null) { addIfNotNull(psiFile.getViewProvider().getBaseLanguage(), set); } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/impl/DirectoryIndexImpl.java b/platform/lang-impl/src/com/intellij/openapi/roots/impl/DirectoryIndexImpl.java index 09e489b3d1df..c753efb145e8 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/impl/DirectoryIndexImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/impl/DirectoryIndexImpl.java @@ -25,14 +25,16 @@ import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.*; +import com.intellij.openapi.roots.ModuleRootAdapter; +import com.intellij.openapi.roots.ModuleRootEvent; +import com.intellij.openapi.roots.ModuleRootManager; +import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; -import com.intellij.util.IncorrectOperationException; import com.intellij.util.Query; import com.intellij.util.containers.ConcurrentIntObjectMap; import com.intellij.util.containers.StripedLockIntObjectConcurrentHashMap; @@ -42,8 +44,6 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.jetbrains.jps.model.module.JpsModuleSourceRootType; -import java.util.Arrays; -import java.util.Collections; import java.util.List; public class DirectoryIndexImpl extends DirectoryIndex { @@ -206,96 +206,4 @@ public class DirectoryIndexImpl extends DirectoryIndex { LOG.error("Directory index is already disposed for " + myProject); } } - - @NotNull - private static OrderEntry createFakeOrderEntry(@NotNull final Module ownerModule) { - return new OrderEntry() { - @NotNull - @Override - public VirtualFile[] getFiles(OrderRootType type) { - throw new IncorrectOperationException(); - } - - @NotNull - @Override - public String[] getUrls(OrderRootType rootType) { - throw new IncorrectOperationException(); - } - - @NotNull - @Override - public String getPresentableName() { - throw new IncorrectOperationException(); - } - - @Override - public boolean isValid() { - throw new IncorrectOperationException(); - } - - @NotNull - @Override - public Module getOwnerModule() { - return ownerModule; - } - - @Override - public <R> R accept(RootPolicy<R> policy, @Nullable R initialValue) { - throw new IncorrectOperationException(); - } - - @Override - public int compareTo(@NotNull OrderEntry o) { - throw new IncorrectOperationException(); - } - - @Override - public boolean isSynthetic() { - throw new IncorrectOperationException(); - } - }; - } - - @Override - @Nullable - OrderEntry findOrderEntryWithOwnerModule(@NotNull DirectoryInfo info, @NotNull Module ownerModule) { - OrderEntry[] entries = getOrderEntries(info); - if (entries.length < 10) { - for (OrderEntry entry : entries) { - if (entry.getOwnerModule() == ownerModule) return entry; - } - return null; - } - int index = Arrays.binarySearch(entries, createFakeOrderEntry(ownerModule), RootIndex.BY_OWNER_MODULE); - return index < 0 ? null : entries[index]; - } - - @Override - @NotNull - List<OrderEntry> findAllOrderEntriesWithOwnerModule(@NotNull DirectoryInfo info, @NotNull Module ownerModule) { - OrderEntry[] entries = getOrderEntries(info); - if (entries.length == 0) return Collections.emptyList(); - - if (entries.length == 1) { - OrderEntry entry = entries[0]; - return entry.getOwnerModule() == ownerModule ? Arrays.asList(entries) : Collections.<OrderEntry>emptyList(); - } - int index = Arrays.binarySearch(entries, createFakeOrderEntry(ownerModule), RootIndex.BY_OWNER_MODULE); - if (index < 0) { - return Collections.emptyList(); - } - int firstIndex = index; - while (firstIndex - 1 >= 0 && entries[firstIndex - 1].getOwnerModule() == ownerModule) { - firstIndex--; - } - int lastIndex = index + 1; - while (lastIndex < entries.length && entries[lastIndex].getOwnerModule() == ownerModule) { - lastIndex++; - } - - OrderEntry[] subArray = new OrderEntry[lastIndex - firstIndex]; - System.arraycopy(entries, firstIndex, subArray, 0, lastIndex - firstIndex); - - return Arrays.asList(subArray); - } } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentRootPanel.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentRootPanel.java index bc10302c9c43..71b9ebcd205d 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentRootPanel.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentRootPanel.java @@ -45,6 +45,7 @@ import org.jetbrains.jps.model.JpsElement; import org.jetbrains.jps.model.module.JpsModuleSourceRootType; import javax.swing.*; +import javax.swing.border.EmptyBorder; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.awt.*; @@ -102,6 +103,7 @@ public abstract class ContentRootPanel extends JPanel { public void initUI() { myHeader = createHeader(); + myHeader.setBorder(new EmptyBorder(0, 8, 0, 0)); this.add(myHeader, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 8, 0), 0, 0)); addFolderGroupComponents(); @@ -198,7 +200,7 @@ public abstract class ContentRootPanel extends JPanel { final Font labelFont = UIUtil.getLabelFont(); titleLabel.setFont(labelFont.deriveFont(Font.BOLD)); titleLabel.setOpaque(false); - titleLabel.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 0)); + titleLabel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); registerTextComponent(titleLabel, foregroundColor); final JPanel groupPanel = new JPanel(new BorderLayout()); diff --git a/platform/lang-impl/src/com/intellij/platform/templates/github/DownloadUtil.java b/platform/lang-impl/src/com/intellij/platform/templates/github/DownloadUtil.java index e4889af6a591..bbffc7c98ba4 100644 --- a/platform/lang-impl/src/com/intellij/platform/templates/github/DownloadUtil.java +++ b/platform/lang-impl/src/com/intellij/platform/templates/github/DownloadUtil.java @@ -176,9 +176,6 @@ public class DownloadUtil { URLConnection urlConnection = HttpConfigurable.getInstance().openConnection(location); HttpURLConnection httpURLConnection = ObjectUtils.tryCast(urlConnection, HttpURLConnection.class); try { - int timeout = (int) TimeUnit.MINUTES.toMillis(2); - urlConnection.setConnectTimeout(timeout); - urlConnection.setReadTimeout(timeout); urlConnection.connect(); InputStream in = urlConnection.getInputStream(); int contentLength = urlConnection.getContentLength(); diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/ScopesOrderDialog.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/ScopesOrderDialog.java index c69a3e5566a2..602de3c8dba5 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/ScopesOrderDialog.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/ScopesOrderDialog.java @@ -64,7 +64,7 @@ public class ScopesOrderDialog extends DialogWrapper { ListUtil.moveSelectedItemsUp(myOptionsList); } }).disableRemoveAction().disableAddAction().createPanel(); - final JLabel descr = new JLabel("<html><p>If file appears in two or more scopes, it will be" + + final JLabel descr = new JLabel("<html><p>If file appears in two or more scopes, it will be " + "inspected with settings of the topmost scope in list above.</p><p/>" + "<p>Scope order is set globally for all inspections in the profile.</p></html>"); descr.setPreferredSize(new Dimension(300, 100)); diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java index 2da5c80a758b..81d0bf651688 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java @@ -16,7 +16,6 @@ package com.intellij.profile.codeInspection.ui; -import com.intellij.CommonBundle; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInsight.daemon.impl.HighlightInfoType; @@ -62,7 +61,6 @@ import com.intellij.profile.codeInspection.ui.table.ScopesAndSeveritiesTable; import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.ui.*; import com.intellij.ui.components.JBLabel; -import com.intellij.ui.treeStructure.Tree; import com.intellij.util.Alarm; import com.intellij.util.Function; import com.intellij.util.config.StorageAccessors; @@ -85,8 +83,6 @@ import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.awt.*; -import java.awt.event.InputEvent; -import java.awt.event.KeyEvent; import java.io.IOException; import java.io.StringReader; import java.util.*; @@ -811,7 +807,7 @@ public class SingleInspectionProfilePanel extends JPanel { } } final JTable scopesAndScopesAndSeveritiesTable = - new ScopesAndSeveritiesTable(new ScopesAndSeveritiesTable.TableSettings(nodes, mySelectedProfile, myTreeTable, project) { + new ScopesAndSeveritiesTable(new ScopesAndSeveritiesTable.TableSettings(nodes, mySelectedProfile, project) { @Override protected void onScopeChosen(@NotNull final ScopeToolState state) { setConfigPanel(configPanelAnchor, state); diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/inspectionsTree/InspectionsConfigTreeTable.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/inspectionsTree/InspectionsConfigTreeTable.java index 92cb62f0f800..5607816ad13c 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/inspectionsTree/InspectionsConfigTreeTable.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/inspectionsTree/InspectionsConfigTreeTable.java @@ -64,8 +64,8 @@ public class InspectionsConfigTreeTable extends TreeTable { final TableColumn isEnabledColumn = getColumnModel().getColumn(IS_ENABLED_COLUMN); isEnabledColumn.setMaxWidth(20); - isEnabledColumn.setCellRenderer(new ThreeStateCheckBoxRenderer(false)); - isEnabledColumn.setCellEditor(new ThreeStateCheckBoxRenderer(true)); + isEnabledColumn.setCellRenderer(new ThreeStateCheckBoxRenderer()); + isEnabledColumn.setCellEditor(new ThreeStateCheckBoxRenderer()); addMouseMotionListener(new MouseAdapter() { @Override diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ScopesAndSeveritiesTable.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ScopesAndSeveritiesTable.java index 3b2c36bf7d34..385b764af027 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ScopesAndSeveritiesTable.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ScopesAndSeveritiesTable.java @@ -20,11 +20,9 @@ import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.ex.Descriptor; import com.intellij.codeInspection.ex.InspectionProfileImpl; import com.intellij.codeInspection.ex.ScopeToolState; -import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopupFactory; @@ -36,12 +34,12 @@ import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionConfigTr import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.table.JBTable; -import com.intellij.ui.treeStructure.treetable.TreeTable; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.EditableModel; +import com.intellij.util.ui.EmptyIcon; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -63,7 +61,7 @@ public class ScopesAndSeveritiesTable extends JBTable { public static final HighlightSeverity MIXED_FAKE_SEVERITY = new HighlightSeverity("Mixed", -1); @SuppressWarnings("UnusedDeclaration") - public static final HighlightDisplayLevel MIXED_FAKE_LEVEL = new HighlightDisplayLevel(MIXED_FAKE_SEVERITY, AllIcons.Actions.Help); + public static final HighlightDisplayLevel MIXED_FAKE_LEVEL = new HighlightDisplayLevel(MIXED_FAKE_SEVERITY, EmptyIcon.create(12)); private final static int SCOPE_ENABLED_COLUMN = 0; private final static int SCOPE_NAME_COLUMN = 1; @@ -76,8 +74,8 @@ public class ScopesAndSeveritiesTable extends JBTable { final TableColumn scopeEnabledColumn = columnModel.getColumn(SCOPE_ENABLED_COLUMN); scopeEnabledColumn.setMaxWidth(30); - scopeEnabledColumn.setCellRenderer(new ThreeStateCheckBoxRenderer(false)); - scopeEnabledColumn.setCellEditor(new ThreeStateCheckBoxRenderer(true)); + scopeEnabledColumn.setCellRenderer(new ThreeStateCheckBoxRenderer()); + scopeEnabledColumn.setCellEditor(new ThreeStateCheckBoxRenderer()); final TableColumn severityColumn = columnModel.getColumn(SEVERITY_COLUMN); severityColumn.setCellRenderer(SeverityRenderer.create(tableSettings.getInspectionProfile())); @@ -113,12 +111,10 @@ public class ScopesAndSeveritiesTable extends JBTable { private final List<String> myKeyNames; private final List<HighlightDisplayKey> myKeys; private final InspectionProfileImpl myInspectionProfile; - private final TreeTable myTreeTable; private final Project myProject; protected TableSettings(final List<InspectionConfigTreeNode> nodes, final InspectionProfileImpl inspectionProfile, - final TreeTable treeTable, final Project project) { myNodes = nodes; myKeys = new ArrayList<HighlightDisplayKey>(myNodes.size()); @@ -130,7 +126,6 @@ public class ScopesAndSeveritiesTable extends JBTable { } myInspectionProfile = inspectionProfile; - myTreeTable = treeTable; myProject = project; } @@ -150,10 +145,6 @@ public class ScopesAndSeveritiesTable extends JBTable { return myInspectionProfile; } - public TreeTable getTreeTable() { - return myTreeTable; - } - public Project getProject() { return myProject; } @@ -186,8 +177,6 @@ public class ScopesAndSeveritiesTable extends JBTable { private static class MyTableModel extends AbstractTableModel implements EditableModel { private final InspectionProfileImpl myInspectionProfile; private final List<String> myKeyNames; - private final List<InspectionConfigTreeNode> myNodes; - private final TreeTable myTreeTable; private final Project myProject; private final TableSettings myTableSettings; private final List<HighlightDisplayKey> myKeys; @@ -202,8 +191,6 @@ public class ScopesAndSeveritiesTable extends JBTable { myInspectionProfile = tableSettings.getInspectionProfile(); myKeys = tableSettings.getKeys(); myKeyNames = tableSettings.getKeyNames(); - myNodes = tableSettings.getNodes(); - myTreeTable = tableSettings.getTreeTable(); myScopeComparator = new ScopeOrderComparator(myInspectionProfile); refreshAggregatedScopes(); } @@ -263,7 +250,7 @@ public class ScopesAndSeveritiesTable extends JBTable { case SCOPE_ENABLED_COLUMN: return isEnabled(rowIndex); case SCOPE_NAME_COLUMN: - return rowIndex == lastRowIndex() ? "Everywhere else" : getScope(rowIndex).getName(); + return rowIndex == lastRowIndex() ? "Everywhere else" : getScopeName(rowIndex); case SEVERITY_COLUMN: return getSeverityState(rowIndex); default: @@ -275,13 +262,17 @@ public class ScopesAndSeveritiesTable extends JBTable { return getScopeToolState(rowIndex).getExistedStates().get(0).getScope(myProject); } + private String getScopeName(final int rowIndex) { + return getScopeToolState(rowIndex).getExistedStates().get(0).getScopeName(); + } + @NotNull private SeverityState getSeverityState(final int rowIndex) { final ExistedScopesStatesAndNonExistNames existedScopesStatesAndNonExistNames = getScopeToolState(rowIndex); if (!existedScopesStatesAndNonExistNames.getNonExistNames().isEmpty()) { return new SeverityState(MIXED_FAKE_SEVERITY, false); } - return new SeverityState(ScopesAndSeveritiesTable.getSeverity(existedScopesStatesAndNonExistNames.getExistedStates()), true); + return new SeverityState(getSeverity(existedScopesStatesAndNonExistNames.getExistedStates()), true); } @Nullable @@ -361,7 +352,7 @@ public class ScopesAndSeveritiesTable extends JBTable { LOG.error("no display level found for name " + severityState.getSeverity().getName()); return; } - final String scopeName = rowIndex == lastRowIndex() ? null : getScope(rowIndex).getName(); + final String scopeName = rowIndex == lastRowIndex() ? null : getScopeName(rowIndex); myInspectionProfile.setErrorLevel(myKeys, level, scopeName, myProject); } else if (columnIndex == SCOPE_ENABLED_COLUMN) { @@ -417,7 +408,6 @@ public class ScopesAndSeveritiesTable extends JBTable { } }; DataContext dataContext = DataManager.getInstance().getDataContext(myTable); - final JComponent component = (JComponent)PlatformDataKeys.CONTEXT_COMPONENT.getData(dataContext); final ListPopup popup = JBPopupFactory.getInstance() .createActionGroupPopup(ScopesChooser.TITLE, scopesChooser.createPopupActionGroup(myTable), dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false); diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ThreeStateCheckBoxRenderer.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ThreeStateCheckBoxRenderer.java index 455e2a60cd19..9e2a4ead10f1 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ThreeStateCheckBoxRenderer.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ThreeStateCheckBoxRenderer.java @@ -27,6 +27,7 @@ import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import java.awt.*; import java.awt.event.*; +import java.util.ArrayList; import java.util.EventObject; import java.util.List; @@ -37,7 +38,7 @@ public class ThreeStateCheckBoxRenderer extends ThreeStateCheckBox implements Ta private final List<CellEditorListener> myListeners = new SmartList<CellEditorListener>(); - public ThreeStateCheckBoxRenderer(final boolean isEditor) { + public ThreeStateCheckBoxRenderer() { setThirdStateEnabled(false); setHorizontalAlignment(CENTER); setVerticalAlignment(CENTER); @@ -95,7 +96,7 @@ public class ThreeStateCheckBoxRenderer extends ThreeStateCheckBox implements Ta @Override public boolean stopCellEditing() { final ChangeEvent e = new ChangeEvent(this); - for (final CellEditorListener listener : myListeners) { + for (final CellEditorListener listener : new ArrayList<CellEditorListener>(myListeners)) { listener.editingStopped(e); } return true; @@ -104,7 +105,7 @@ public class ThreeStateCheckBoxRenderer extends ThreeStateCheckBox implements Ta @Override public void cancelCellEditing() { final ChangeEvent e = new ChangeEvent(this); - for (final CellEditorListener listener : myListeners) { + for (final CellEditorListener listener : new ArrayList<CellEditorListener>(myListeners)) { listener.editingCanceled(e); } } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/DocumentCommitThread.java b/platform/lang-impl/src/com/intellij/psi/impl/DocumentCommitThread.java index c8793c085a58..32a2e38384d9 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/DocumentCommitThread.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/DocumentCommitThread.java @@ -18,8 +18,8 @@ package com.intellij.psi.impl; import com.intellij.codeInsight.daemon.impl.DaemonProgressIndicator; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.openapi.Disposable; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.ex.ApplicationManagerEx; +import com.intellij.openapi.application.ApplicationAdapter; +import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; @@ -54,17 +54,44 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run private final Queue<CommitTask> documentsToCommit = new Queue<CommitTask>(10); private final List<CommitTask> documentsToApplyInEDT = new ArrayList<CommitTask>(10); // guarded by documentsToCommit + private final ApplicationEx myApplication; private volatile boolean isDisposed; private CommitTask currentTask; // guarded by documentsToCommit private volatile boolean threadFinished; - private volatile boolean myEnabled = true; // true if we can do commits. set to false temporarily during the write action. + private volatile boolean myEnabled; // true if we can do commits. set to false temporarily during the write action. public static DocumentCommitThread getInstance() { return ServiceManager.getService(DocumentCommitThread.class); } - public DocumentCommitThread() { - log("Starting thread",null, false); + public DocumentCommitThread(final ApplicationEx application) { + myApplication = application; + // install listener in EDT to avoid missing events in case we are inside write action right now + application.invokeLater(new Runnable() { + @Override + public void run() { + application.addApplicationListener(new ApplicationAdapter() { + private int runningWriteActions; + + @Override + public void beforeWriteActionStart(Object action) { + if (runningWriteActions++ == 0) { + disable("Write action started: " + action); + } + } + + @Override + public void writeActionFinished(Object action) { + if (--runningWriteActions == 0) { + enable("Write action finished: " + action); + } + } + }, DocumentCommitThread.this); + + enable("Listener installed, started"); + } + }); + log("Starting thread", null, false); new Thread(this, "Document commit thread").start(); } @@ -88,14 +115,14 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run } } - public void disable(@NonNls Object reason) { + private void disable(@NonNls Object reason) { // write action has just started, all commits are useless cancel(reason); myEnabled = false; log("Disabled", null, false, reason); } - public void enable(Object reason) { + private void enable(@NonNls Object reason) { myEnabled = true; wakeUpQueue(); log("Enabled", null, false, reason); @@ -107,7 +134,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run } } - private void cancel(@NonNls Object reason) { + private void cancel(@NonNls @NotNull Object reason) { startNewTask(null, reason); } @@ -126,7 +153,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run doQueue(project, document, reason); } - private void doQueue(Project project, Document document, Object reason) { + private void doQueue(@NotNull Project project, @NotNull Document document, @NotNull Object reason) { synchronized (documentsToCommit) { ProgressIndicator indicator = new DaemonProgressIndicator(); CommitTask newTask = new CommitTask(document, project, indicator, reason); @@ -193,7 +220,6 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run public void clearQueue() { cancelAll(); log.setLength(0); - disable("end of test"); wakeUpQueue(); } @@ -303,9 +329,9 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run } if (success) { - assert !ApplicationManager.getApplication().isDispatchThread(); + assert !myApplication.isDispatchThread(); UIUtil.invokeLaterIfNeeded(finishRunnable); - log("Invoked later finishRunnable", task, false, success, finishRunnable, indicator); + log("Invoked later finishRunnable", task, false, finishRunnable, indicator); } } catch (ProcessCanceledException e) { @@ -334,7 +360,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run @Override public void commitSynchronously(@NotNull Document document, @NotNull Project project) { assert !isDisposed; - ApplicationManager.getApplication().assertWriteAccessAllowed(); + myApplication.assertWriteAccessAllowed(); if (!project.isInitialized() && !project.isDefault()) { @NonNls String s = project + "; Disposed: "+project.isDisposed()+"; Open: "+project.isOpen(); @@ -380,7 +406,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run return new ProgressIndicatorBase(); } - private void startNewTask(CommitTask task, Object reason) { + private void startNewTask(@Nullable CommitTask task, @NotNull Object reason) { synchronized (documentsToCommit) { // sync to prevent overwriting CommitTask cur = currentTask; if (cur != null) { @@ -388,19 +414,19 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run } currentTask = task; } + log("new task started", task, false, reason); } // returns finish commit Runnable (to be invoked later in EDT), or null on failure @Nullable - private Runnable commitUnderProgress(@NotNull final CommitTask task, - final boolean synchronously) { + private Runnable commitUnderProgress(@NotNull final CommitTask task, final boolean synchronously) { final Project project = task.project; final Document document = task.document; final List<Processor<Document>> finishProcessors = new SmartList<Processor<Document>>(); Runnable runnable = new Runnable() { @Override public void run() { - ApplicationManager.getApplication().assertReadAccessAllowed(); + myApplication.assertReadAccessAllowed(); if (project.isDisposed()) return; final PsiDocumentManagerImpl documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(project); @@ -424,14 +450,12 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run } }; if (synchronously) { - ApplicationManager.getApplication().assertWriteAccessAllowed(); + myApplication.assertWriteAccessAllowed(); runnable.run(); } - else { - if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(runnable)) { - log("Could not start read action", task, synchronously, ApplicationManager.getApplication().isReadAccessAllowed(), Thread.currentThread()); - return null; - } + else if (!myApplication.tryRunReadAction(runnable)) { + log("Could not start read action", task, synchronously, myApplication.isReadAccessAllowed(), Thread.currentThread()); + return null; } boolean canceled = task.indicator.isCanceled(); @@ -443,7 +467,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run Runnable finishRunnable = new Runnable() { @Override public void run() { - ApplicationManager.getApplication().assertIsDispatchThread(); + myApplication.assertIsDispatchThread(); Project project = task.project; if (project.isDisposed()) return; @@ -525,4 +549,27 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run } return result[0]; } + + @TestOnly + boolean isEnabled() { + return myEnabled; + } + + @TestOnly + public void waitUntilAllCommitted(long timeout) throws InterruptedException { + if (!myEnabled) { + throw new IllegalStateException("DocumentCommitThread is disabled"); + } + int attempts = 0; + int delay = 100; + synchronized (documentsToCommit) { + while(!documentsToCommit.isEmpty() || currentTask != null) { + documentsToCommit.wait(delay); + if (delay * attempts > timeout) { + throw new RuntimeException("timeout"); + } + attempts++; + } + } + } } 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 63b8a6af86e1..16926b18b834 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/PsiDocumentManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/PsiDocumentManagerImpl.java @@ -19,7 +19,6 @@ package com.intellij.psi.impl; import com.intellij.AppTopics; import com.intellij.injected.editor.DocumentWindow; import com.intellij.injected.editor.EditorWindowImpl; -import com.intellij.openapi.application.ApplicationAdapter; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.SettingsSavingComponent; import com.intellij.openapi.editor.Document; @@ -33,7 +32,10 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectLocator; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; +import com.intellij.psi.FileViewProvider; +import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiManager; +import com.intellij.psi.SmartPointerManager; import com.intellij.psi.impl.source.PostprocessReformattingAspect; import com.intellij.util.FileContentUtil; import com.intellij.util.Processor; @@ -79,18 +81,6 @@ public class PsiDocumentManagerImpl extends PsiDocumentManagerBase implements Se documentCommitThread.queueCommit(project, doc, "Bulk update finished"); } }); - ApplicationManager.getApplication().addApplicationListener(new ApplicationAdapter() { - @Override - public void beforeWriteActionStart(Object action) { - documentCommitThread.disable("Write action started: " + action); - } - - @Override - public void writeActionFinished(Object action) { - documentCommitThread.enable("Write action finished: " + action); - } - }, project); - documentCommitThread.enable("project open"); } @Nullable diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeFormatterFacade.java b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeFormatterFacade.java index fa1dd9e86b4a..c7b9bf3a3adf 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeFormatterFacade.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeFormatterFacade.java @@ -391,14 +391,15 @@ public class CodeFormatterFacade { /** - * Inspects all lines of the given document and wraps all of them that exceed {@link CodeStyleSettings#RIGHT_MARGIN right margin}. + * Inspects all lines of the given document and wraps all of them that exceed {@link CodeStyleSettings#getRightMargin(com.intellij.lang.Language)} + * right margin}. * <p/> * I.e. the algorithm is to do the following for every line: * <p/> * <pre> * <ol> * <li> - * Check if the line exceeds {@link CodeStyleSettings#RIGHT_MARGIN right margin}. Go to the next line in the case of + * Check if the line exceeds {@link CodeStyleSettings#getRightMargin(com.intellij.lang.Language)} right margin}. Go to the next line in the case of * negative answer; * </li> * <li>Determine line wrap position; </li> diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java index 767152fc1e2b..d51ef1216a59 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java @@ -181,7 +181,7 @@ public class CodeStyleManagerImpl extends CodeStyleManager { transformAllChildren(treeElement); final CodeFormatterFacade codeFormatter = new CodeFormatterFacade(getSettings(), file.getLanguage()); - LOG.assertTrue(file.isValid()); + LOG.assertTrue(file.isValid(), "File name: " + file.getName() + " , class: " + file.getClass().getSimpleName()); if (editor == null) { editor = PsiUtilBase.findEditor(file); diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/PsiCommentImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/PsiCommentImpl.java deleted file mode 100644 index d4e1b0d52f53..000000000000 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/PsiCommentImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2000-2009 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.psi.impl.source.tree; - -import com.intellij.psi.LiteralTextEscaper; -import com.intellij.psi.PsiLanguageInjectionHost; -import com.intellij.psi.impl.source.tree.injected.CommentLiteralEscaper; -import com.intellij.psi.tree.IElementType; -import org.jetbrains.annotations.NotNull; - -public class PsiCommentImpl extends PsiCoreCommentImpl implements PsiLanguageInjectionHost { - public PsiCommentImpl(IElementType type, CharSequence text) { - super(type, text); - } - - @Override - public boolean isValidHost() { - return true; - } - - @Override - public PsiLanguageInjectionHost updateText(@NotNull final String text) { - return (PsiCommentImpl)replaceWithText(text); - } - - @Override - @NotNull - public LiteralTextEscaper<PsiCommentImpl> createLiteralTextEscaper() { - return new CommentLiteralEscaper(this); - } -} diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/CommentLiteralEscaper.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/CommentLiteralEscaper.java deleted file mode 100644 index c6399e30b5f6..000000000000 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/CommentLiteralEscaper.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2000-2009 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.psi.impl.source.tree.injected; - -import com.intellij.openapi.util.ProperTextRange; -import com.intellij.lang.CodeDocumentationAwareCommenter; -import com.intellij.lang.Commenter; -import com.intellij.lang.LanguageCommenters; -import com.intellij.openapi.util.TextRange; -import com.intellij.psi.LiteralTextEscaper; -import com.intellij.psi.impl.source.tree.PsiCommentImpl; -import org.jetbrains.annotations.NotNull; - -/** - * @author cdr -*/ -public class CommentLiteralEscaper extends LiteralTextEscaper<PsiCommentImpl> { - public CommentLiteralEscaper(PsiCommentImpl host) { - super(host); - } - - @Override - public boolean decode(@NotNull final TextRange rangeInsideHost, @NotNull StringBuilder outChars) { - ProperTextRange.assertProperRange(rangeInsideHost); - outChars.append(myHost.getText(), rangeInsideHost.getStartOffset(), rangeInsideHost.getEndOffset()); - return true; - } - - @Override - public int getOffsetInHost(int offsetInDecoded, @NotNull final TextRange rangeInsideHost) { - int offset = offsetInDecoded + rangeInsideHost.getStartOffset(); - if (offset < rangeInsideHost.getStartOffset()) offset = rangeInsideHost.getStartOffset(); - if (offset > rangeInsideHost.getEndOffset()) offset = rangeInsideHost.getEndOffset(); - return offset; - } - - @Override - public boolean isOneLine() { - final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(myHost.getLanguage()); - if (commenter instanceof CodeDocumentationAwareCommenter) { - return myHost.getTokenType() == ((CodeDocumentationAwareCommenter) commenter).getLineCommentTokenType(); - } - return false; - } -}
\ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedFileViewProvider.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedFileViewProvider.java index f4a6d576e6b8..58a9463b755d 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedFileViewProvider.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedFileViewProvider.java @@ -61,7 +61,7 @@ public class InjectedFileViewProvider extends SingleRootFileViewProvider impleme @NotNull Language language) { super(psiManager, (VirtualFile)virtualFile, true, language); myDocumentWindow = documentWindow; - myProject = documentWindow.getShreds().get(0).getHost().getProject(); + myProject = documentWindow.getShreds().getHostPointer().getProject(); } @Override diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageUtil.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageUtil.java index fdc434d8d11a..647ace567d5d 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageUtil.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageUtil.java @@ -24,7 +24,6 @@ import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; @@ -38,6 +37,7 @@ import com.intellij.psi.impl.PsiParameterizedCachedValue; import com.intellij.psi.impl.source.DummyHolder; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.*; +import com.intellij.testFramework.LightVirtualFile; import com.intellij.util.containers.ConcurrentList; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; @@ -93,7 +93,12 @@ public class InjectedLanguageUtil { public static Place getShreds(@NotNull FileViewProvider viewProvider) { if (!(viewProvider instanceof InjectedFileViewProvider)) return null; InjectedFileViewProvider myFileViewProvider = (InjectedFileViewProvider)viewProvider; - return ((DocumentWindowImpl)myFileViewProvider.getDocument()).getShreds(); + return getShreds(myFileViewProvider.getDocument()); + } + + @NotNull + public static Place getShreds(@NotNull DocumentWindow document) { + return ((DocumentWindowImpl)document).getShreds(); } public static void enumerate(@NotNull DocumentWindow documentWindow, @@ -162,6 +167,13 @@ public class InjectedLanguageUtil { return getEditorForInjectedLanguageNoCommit(editor, file, offset); } + public static Editor getEditorForInjectedLanguageNoCommit(@Nullable Editor editor, @Nullable Caret caret, @Nullable PsiFile file) { + if (editor == null || file == null || editor instanceof EditorWindow || caret == null) return editor; + + PsiFile injectedFile = findInjectedPsiNoCommit(file, caret.getOffset()); + return getInjectedEditorForInjectedFile(editor, caret, injectedFile); + } + public static Caret getCaretForInjectedLanguageNoCommit(@Nullable Caret caret, @Nullable PsiFile file) { if (caret == null || file == null || caret instanceof InjectedCaret) return caret; @@ -212,17 +224,21 @@ public class InjectedLanguageUtil { @NotNull public static Editor getInjectedEditorForInjectedFile(@NotNull Editor hostEditor, @Nullable final PsiFile injectedFile) { + return getInjectedEditorForInjectedFile(hostEditor, hostEditor.getCaretModel().getCurrentCaret(), injectedFile); + } + + @NotNull + public static Editor getInjectedEditorForInjectedFile(@NotNull Editor hostEditor, @NotNull Caret hostCaret, @Nullable final PsiFile injectedFile) { if (injectedFile == null || hostEditor instanceof EditorWindow || hostEditor.isDisposed()) return hostEditor; Project project = hostEditor.getProject(); if (project == null) project = injectedFile.getProject(); Document document = PsiDocumentManager.getInstance(project).getDocument(injectedFile); if (!(document instanceof DocumentWindowImpl)) return hostEditor; DocumentWindowImpl documentWindow = (DocumentWindowImpl)document; - SelectionModel selectionModel = hostEditor.getSelectionModel(); - if (selectionModel.hasSelection()) { - int selstart = selectionModel.getSelectionStart(); + if (hostCaret.hasSelection()) { + int selstart = hostCaret.getSelectionStart(); if (selstart != -1) { - int selend = Math.max(selstart, selectionModel.getSelectionEnd()); + int selend = Math.max(selstart, hostCaret.getSelectionEnd()); if (!documentWindow.containsRange(selstart, selend)) { // selection spreads out the injected editor range return hostEditor; @@ -573,4 +589,29 @@ public class InjectedLanguageUtil { }); return ref.get(); } + + @Nullable + public static PsiLanguageInjectionHost findInjectionHost(@Nullable PsiElement psi) { + if (psi == null) return null; + PsiFile containingFile = psi.getContainingFile().getOriginalFile(); // * formatting + PsiElement fileContext = containingFile.getContext(); // * quick-edit-handler + if (fileContext instanceof PsiLanguageInjectionHost) return (PsiLanguageInjectionHost)fileContext; + Place shreds = getShreds(containingFile.getViewProvider()); // * injection-registrar + if (shreds == null) { + VirtualFile virtualFile = PsiUtilCore.getVirtualFile(containingFile); + if (virtualFile instanceof LightVirtualFile) { + virtualFile = ((LightVirtualFile)virtualFile).getOriginalFile(); // * dynamic files-from-text + } + if (virtualFile instanceof VirtualFileWindow) { + shreds = getShreds(((VirtualFileWindow)virtualFile).getDocumentWindow()); + } + } + return shreds != null ? shreds.getHostPointer().getElement() : null; + } + + @Nullable + public static PsiLanguageInjectionHost findInjectionHost(@Nullable VirtualFile virtualFile) { + return virtualFile instanceof VirtualFileWindow ? + getShreds(((VirtualFileWindow)virtualFile).getDocumentWindow()).getHostPointer().getElement() : null; + } } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java index 183af7374072..e520eea741be 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java @@ -389,7 +389,7 @@ public class MultiHostRegistrarImpl implements MultiHostRegistrar, ModificationT "\nLeaf texts concatenated:'"+ patcher.catLeafs +"';" + "\nFile root: "+parsedNode+ "\nLanguage: "+parsedNode.getPsi().getLanguage()+ - "\nHost file: "+ shreds.get(0).getHost().getContainingFile().getVirtualFile() + "\nHost file: "+ shreds.getHostPointer().getVirtualFile() ; DebugUtil.startPsiModification("injection leaf patching"); try { diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/Place.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/Place.java index afaf499b9bb9..f6be385077c2 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/Place.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/Place.java @@ -17,6 +17,7 @@ package com.intellij.psi.impl.source.tree.injected; import com.intellij.psi.PsiLanguageInjectionHost; +import com.intellij.psi.SmartPsiElementPointer; import com.intellij.util.SmartList; import org.jetbrains.annotations.NotNull; @@ -30,6 +31,11 @@ public class Place extends SmartList<PsiLanguageInjectionHost.Shred> { super(shreds); } + @NotNull + public SmartPsiElementPointer<PsiLanguageInjectionHost> getHostPointer() { + return ((ShredImpl)get(0)).getSmartPointer(); + } + public boolean isValid() { for (PsiLanguageInjectionHost.Shred shred : this) { if (!shred.isValid()) { diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/ShredImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/ShredImpl.java index aea41ab16f72..5c60a1c2254f 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/ShredImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/ShredImpl.java @@ -45,6 +45,7 @@ class ShredImpl implements PsiLanguageInjectionHost.Shred { assert relevantRangeInHost.isValid(); } + @NotNull public SmartPsiElementPointer<PsiLanguageInjectionHost> getSmartPointer() { return hostElementPointer; } diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java index d791f14aa841..493d1d6cd519 100644 --- a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java @@ -302,7 +302,7 @@ public class StubIndexImpl extends StubIndex implements ApplicationComponent, Pe return true; } - private static void forceRebuild(@NotNull Throwable e) { + public void forceRebuild(@NotNull Throwable e) { LOG.info(e); FileBasedIndex.getInstance().scheduleRebuild(StubUpdatingIndex.INDEX_ID, e); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MethodNodeBase.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MethodNodeBase.java index 36e5352e0f8e..782ff452fbf4 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MethodNodeBase.java +++ b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/MethodNodeBase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.intellij.refactoring.changeSignature; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; @@ -88,7 +89,12 @@ public abstract class MethodNodeBase<M extends PsiElement> extends CheckedTreeNo if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { @Override public void run() { - callers.set(computeCallers()); + ApplicationManager.getApplication().runReadAction(new Runnable() { + @Override + public void run() { + callers.set(computeCallers()); + } + }); } }, RefactoringBundle.message("caller.chooser.looking.for.callers"), true, myProject)) { myCancelCallback.run(); diff --git a/platform/lang-impl/src/com/intellij/refactoring/inline/GenericInlineHandler.java b/platform/lang-impl/src/com/intellij/refactoring/inline/GenericInlineHandler.java index dd5d9a42ed91..cbeefc786612 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/inline/GenericInlineHandler.java +++ b/platform/lang-impl/src/com/intellij/refactoring/inline/GenericInlineHandler.java @@ -184,7 +184,7 @@ public class GenericInlineHandler { } } else { - conflicts.putValue(referenceElement, "Cannot inline reference from " + language.getID()); + conflicts.putValue(referenceElement, "Cannot inline reference from " + language.getDisplayName()); } } diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java index 7e8ec09f3e23..a34d30dc5401 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java @@ -320,11 +320,7 @@ public class RenameProcessor extends BaseRefactoringProcessor { protected boolean isPreviewUsages(UsageInfo[] usages) { if (myForceShowPreview) return true; if (super.isPreviewUsages(usages)) return true; - if (UsageViewUtil.hasNonCodeUsages(usages)) { - WindowManager.getInstance().getStatusBar(myProject) - .setInfo(RefactoringBundle.message("occurrences.found.in.comments.strings.and.non.java.files")); - return true; - } + if (UsageViewUtil.reportNonRegularUsages(usages, myProject)) return true; return false; } diff --git a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java index e6acbaa4adda..b8f069d5f142 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java @@ -26,7 +26,6 @@ import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Ref; -import com.intellij.openapi.wm.WindowManager; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ReferencesSearch; @@ -40,7 +39,9 @@ import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteCustomUsageInfo; import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteReferenceSimpleDeleteUsageInfo; import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteReferenceUsageInfo; import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteUsageInfo; -import com.intellij.refactoring.util.*; +import com.intellij.refactoring.util.NonCodeSearchDescriptionLocation; +import com.intellij.refactoring.util.RefactoringUIUtil; +import com.intellij.refactoring.util.TextOccurrencesUtil; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; import com.intellij.usageView.UsageViewUtil; @@ -352,8 +353,7 @@ public class SafeDeleteProcessor extends BaseRefactoringProcessor { @Override protected boolean isPreviewUsages(UsageInfo[] usages) { - if(myPreviewNonCodeUsages && (UsageViewUtil.hasNonCodeUsages(usages) || UsageViewUtil.hasUsagesInGeneratedCode(usages, myProject))) { - WindowManager.getInstance().getStatusBar(myProject).setInfo(RefactoringBundle.message("occurrences.found.in.comments.strings.non.java.files.and.generated.code")); + if(myPreviewNonCodeUsages && UsageViewUtil.reportNonRegularUsages(usages, myProject)) { return true; } diff --git a/platform/lang-impl/src/com/intellij/tools/BaseToolManager.java b/platform/lang-impl/src/com/intellij/tools/BaseToolManager.java index c848939cf398..478f60eed51a 100644 --- a/platform/lang-impl/src/com/intellij/tools/BaseToolManager.java +++ b/platform/lang-impl/src/com/intellij/tools/BaseToolManager.java @@ -1,6 +1,6 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,10 +33,10 @@ import java.util.List; public abstract class BaseToolManager<T extends Tool> implements ExportableApplicationComponent { - private final ActionManagerEx myActionManager; + @NotNull private final ActionManagerEx myActionManager; private final SchemesManager<ToolsGroup<T>, ToolsGroup<T>> mySchemesManager; - public BaseToolManager(ActionManagerEx actionManagerEx, SchemesManagerFactory factory) { + public BaseToolManager(@NotNull ActionManagerEx actionManagerEx, SchemesManagerFactory factory) { myActionManager = actionManagerEx; mySchemesManager = factory.createSchemesManager( diff --git a/platform/lang-impl/src/com/intellij/tools/ScanSourceCommentsAction.java b/platform/lang-impl/src/com/intellij/tools/ScanSourceCommentsAction.java index be3fa32182de..53d15d581927 100644 --- a/platform/lang-impl/src/com/intellij/tools/ScanSourceCommentsAction.java +++ b/platform/lang-impl/src/com/intellij/tools/ScanSourceCommentsAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ package com.intellij.tools; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.actionSystem.PlatformDataKeys; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.progress.ProgressIndicator; @@ -107,19 +107,24 @@ public class ScanSourceCommentsAction extends AnAction { descriptor.addFile(file); } - private void scanCommentsInFile(Project project, final VirtualFile vFile) { + private void scanCommentsInFile(final Project project, final VirtualFile vFile) { if (!vFile.isDirectory() && vFile.getFileType() instanceof LanguageFileType) { - PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile); - if (psiFile == null) return; - - for (PsiFile root : psiFile.getViewProvider().getAllFiles()) { - root.accept(new PsiRecursiveElementWalkingVisitor() { - @Override - public void visitComment(PsiComment comment) { - commentFound(vFile, comment.getText()); + ApplicationManager.getApplication().runReadAction(new Runnable() { + @Override + public void run() { + PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile); + if (psiFile == null) return; + + for (PsiFile root : psiFile.getViewProvider().getAllFiles()) { + root.accept(new PsiRecursiveElementWalkingVisitor() { + @Override + public void visitComment(PsiComment comment) { + commentFound(vFile, comment.getText()); + } + }); } - }); - } + } + }); } } diff --git a/platform/lang-impl/src/com/intellij/tools/Tool.java b/platform/lang-impl/src/com/intellij/tools/Tool.java index 760fb5901e65..8077bf530e37 100644 --- a/platform/lang-impl/src/com/intellij/tools/Tool.java +++ b/platform/lang-impl/src/com/intellij/tools/Tool.java @@ -17,7 +17,6 @@ package com.intellij.tools; import com.intellij.execution.ExecutionException; -import com.intellij.execution.RunnerRegistry; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.PathEnvironmentVariableUtil; import com.intellij.execution.executors.DefaultRunExecutor; @@ -274,15 +273,11 @@ public class Tool implements SchemeElement { FileDocumentManager.getInstance().saveAllDocuments(); try { if (isUseConsole()) { - final ToolRunProfile profile = new ToolRunProfile(this, dataContext); - final ProgramRunner runner = RunnerRegistry.getInstance().getRunner(DefaultRunExecutor.EXECUTOR_ID, profile); - assert runner != null; - - ExecutionEnvironment executionEnvironment = new ExecutionEnvironmentBuilder(project, DefaultRunExecutor.getRunExecutorInstance()) - .setRunProfile(profile) - .build(); - executionEnvironment.setExecutionId(executionId); - runner.execute(executionEnvironment, new ProgramRunner.Callback() { + ExecutionEnvironment environment = ExecutionEnvironmentBuilder.create(project, + DefaultRunExecutor.getRunExecutorInstance(), + new ToolRunProfile(this, dataContext)).build(); + environment.setExecutionId(executionId); + environment.getRunner().execute(environment, new ProgramRunner.Callback() { @Override public void processStarted(RunContentDescriptor descriptor) { ProcessHandler processHandler = descriptor.getProcessHandler(); diff --git a/platform/lang-impl/src/com/intellij/ui/DuplicateNodeRenderer.java b/platform/lang-impl/src/com/intellij/ui/DuplicateNodeRenderer.java index 3083ffed6de9..663dccce5ed8 100644 --- a/platform/lang-impl/src/com/intellij/ui/DuplicateNodeRenderer.java +++ b/platform/lang-impl/src/com/intellij/ui/DuplicateNodeRenderer.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.util.Enumeration; @@ -84,9 +85,9 @@ public class DuplicateNodeRenderer { private static Rectangle getExpandedNodesRect(JTree tree, DefaultMutableTreeNode node, TreePath path) { Rectangle rect = tree.getRowBounds(tree.getRowForPath(path)); if (tree.isExpanded(path)) { - Enumeration<DefaultMutableTreeNode> children = node.children(); + Enumeration<TreeNode> children = node.children(); while (children.hasMoreElements()) { - DefaultMutableTreeNode child = children.nextElement(); + DefaultMutableTreeNode child = (DefaultMutableTreeNode)children.nextElement(); TreePath childPath = path.pathByAddingChild(child); assert !path.equals(childPath) : path+";"+child; rect = union(rect, getExpandedNodesRect(tree, child, childPath)); diff --git a/platform/lang-impl/src/com/intellij/ui/popup/PopupPositionManager.java b/platform/lang-impl/src/com/intellij/ui/popup/PopupPositionManager.java index ea9a263d5713..81d09d7886f8 100644 --- a/platform/lang-impl/src/com/intellij/ui/popup/PopupPositionManager.java +++ b/platform/lang-impl/src/com/intellij/ui/popup/PopupPositionManager.java @@ -53,7 +53,7 @@ public class PopupPositionManager { @Nullable final Editor editor, @Nullable DataContext dataContext) { final LookupEx lookup = LookupManager.getActiveLookup(editor); - if (lookup != null && lookup.getCurrentItem() != null) { + if (lookup != null && lookup.getCurrentItem() != null && lookup.getComponent().isShowing()) { new PositionAdjuster(lookup.getComponent()).adjust(hint); lookup.addLookupListener(new LookupAdapter() { @Override diff --git a/platform/lang-impl/src/com/intellij/ui/tabs/ColorSelectionComponent.java b/platform/lang-impl/src/com/intellij/ui/tabs/ColorSelectionComponent.java index a7721a8b826f..bfa1e14ec88e 100644 --- a/platform/lang-impl/src/com/intellij/ui/tabs/ColorSelectionComponent.java +++ b/platform/lang-impl/src/com/intellij/ui/tabs/ColorSelectionComponent.java @@ -96,24 +96,24 @@ public class ColorSelectionComponent extends JPanel { } @Nullable - private ColorButton getSelectedButtonInner() { + public String getSelectedColorName() { for (String name : myColorToButtonMap.keySet()) { ColorButton button = myColorToButtonMap.get(name); - if (button.isSelected()) return button; + if (!button.isSelected()) continue; + if (button instanceof CustomColorButton) return ColorUtil.toHex(button.getColor()); + return name; } return null; } @Nullable - public String getSelectedColorName() { - ColorButton button = getSelectedButtonInner(); - return button == null? null : button instanceof CustomColorButton ? ColorUtil.toHex(button.getColor()) : button.getText(); - } - - @Nullable public Color getSelectedColor() { - ColorButton button = getSelectedButtonInner(); - return button == null? null : button.getColor(); + for (String name : myColorToButtonMap.keySet()) { + ColorButton button = myColorToButtonMap.get(name); + if (!button.isSelected()) continue; + return button.getColor(); + } + return null; } public void initDefault(@NotNull FileColorManager manager, @Nullable String selectedColorName) { diff --git a/platform/lang-impl/src/com/intellij/ui/tabs/FileColorManagerImpl.java b/platform/lang-impl/src/com/intellij/ui/tabs/FileColorManagerImpl.java index a60889bb9f93..c65af1ecdb4f 100644 --- a/platform/lang-impl/src/com/intellij/ui/tabs/FileColorManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/ui/tabs/FileColorManagerImpl.java @@ -18,24 +18,25 @@ package com.intellij.ui.tabs; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.components.*; -import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiManager; import com.intellij.ui.ColorUtil; import com.intellij.ui.FileColorManager; +import com.intellij.ui.JBColor; import com.intellij.ui.LightColors; -import com.intellij.util.containers.hash.LinkedHashMap; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; -import java.util.*; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Map; /** * @author spleaner @@ -52,25 +53,14 @@ public class FileColorManagerImpl extends FileColorManager implements Persistent private final FileColorsModel myModel; private FileColorSharedConfigurationManager mySharedConfigurationManager; - private static final Map<String, Color> ourDefaultColors; - private static final Map<String, Color> ourDefaultDarkColors; - - static { - ourDefaultColors = new LinkedHashMap<String, Color>(); - ourDefaultColors.put("Blue", new Color(0xdcf0ff)); - ourDefaultColors.put("Green", new Color(231, 250, 219)); - ourDefaultColors.put("Orange", new Color(246, 224, 202)); - ourDefaultColors.put("Rose", new Color(242, 206, 202)); - ourDefaultColors.put("Violet", new Color(222, 213, 241)); - ourDefaultColors.put("Yellow", new Color(255, 255, 228)); - ourDefaultDarkColors = new LinkedHashMap<String, Color>(); - ourDefaultDarkColors.put("Blue", new Color(0x2B3557)); - ourDefaultDarkColors.put("Green", new Color(0x2A3B2C)); - ourDefaultDarkColors.put("Orange", new Color(0x823B1C)); - ourDefaultDarkColors.put("Rose", new Color(0x542F3A)); - ourDefaultDarkColors.put("Violet", new Color(0x4f4056)); - ourDefaultDarkColors.put("Yellow", new Color(0x494539)); - } + private static final Map<String, Color> ourDefaultColors = ContainerUtil.<String, Color>immutableMapBuilder() + .put("Blue", new JBColor(new Color(0xdcf0ff), new Color(0x2B3557))) + .put("Green", new JBColor(new Color(231, 250, 219), new Color(0x2A3B2C))) + .put("Orange", new JBColor(new Color(246, 224, 202), new Color(0x823B1C))) + .put("Rose", new JBColor(new Color(242, 206, 202), new Color(0x542F3A))) + .put("Violet", new JBColor(new Color(222, 213, 241), new Color(0x4f4056))) + .put("Yellow", new JBColor(new Color(255, 255, 228), new Color(0x494539))) + .build(); public FileColorManagerImpl(@NotNull final Project project) { myProject = project; @@ -133,7 +123,7 @@ public class FileColorManagerImpl extends FileColorManager implements Persistent @SuppressWarnings({"MethodMayBeStatic"}) @Nullable public Color getColor(@NotNull final String name) { - final Color color = UIUtil.isUnderDarcula() ? ourDefaultDarkColors.get(name) : ourDefaultColors.get(name); + Color color = ourDefaultColors.get(name); return color == null ? ColorUtil.fromHex(name, null) : color; } @@ -151,8 +141,7 @@ public class FileColorManagerImpl extends FileColorManager implements Persistent @Override @SuppressWarnings({"MethodMayBeStatic"}) public Collection<String> getColorNames() { - final Set<String> names = ourDefaultColors.keySet(); - final List<String> sorted = new ArrayList<String>(names); + List<String> sorted = ContainerUtil.newArrayList(ourDefaultColors.keySet()); Collections.sort(sorted); return sorted; } diff --git a/platform/lang-impl/src/com/intellij/usageView/UsageViewUtil.java b/platform/lang-impl/src/com/intellij/usageView/UsageViewUtil.java index ca230c790e65..4dee56707ae0 100644 --- a/platform/lang-impl/src/com/intellij/usageView/UsageViewUtil.java +++ b/platform/lang-impl/src/com/intellij/usageView/UsageViewUtil.java @@ -24,10 +24,13 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.GeneratedSourcesFilter; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.wm.StatusBar; +import com.intellij.openapi.wm.WindowManager; import com.intellij.psi.ElementDescriptionUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; +import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.util.MoveRenameUsageInfo; import com.intellij.refactoring.util.NonCodeUsageInfo; import com.intellij.usages.Usage; @@ -179,4 +182,17 @@ public class UsageViewUtil { } return usageInfos; } + + public static boolean reportNonRegularUsages(UsageInfo[] usages, final Project project) { + boolean inGeneratedCode = hasUsagesInGeneratedCode(usages, project); + if (hasNonCodeUsages(usages) || inGeneratedCode) { + StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); + if (statusBar != null) { + statusBar.setInfo(inGeneratedCode ? RefactoringBundle.message("occurrences.found.in.comments.strings.non.java.files.and.generated.code") + : RefactoringBundle.message("occurrences.found.in.comments.strings.and.non.java.files")); + } + return true; + } + return false; + } } diff --git a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java index 85077380ea6e..da85132806e5 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java @@ -531,7 +531,8 @@ public class FileBasedIndexImpl extends FileBasedIndex { extension.hasSnapshotMapping() && IdIndex.ourSnapshotMappingsEnabled ? createInputsIndexExternalizer(extension, indexId, extension.getKeyDescriptor()) : null; - index = new MapReduceIndex<K, V, FileContent>(indexId, extension.getIndexer(), storage, externalizer, extension.getValueExternalizer()); + index = new MapReduceIndex<K, V, FileContent>( + indexId, extension.getIndexer(), storage, externalizer, extension.getValueExternalizer(), extension instanceof PsiDependentIndex); } index.setInputIdToDataKeysIndex(new Factory<PersistentHashMap<Integer, Collection<K>>>() { @Override diff --git a/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java b/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java index 6427765295c5..0060cb2fb159 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java @@ -17,10 +17,14 @@ package com.intellij.util.indexing; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.editor.Document; +import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream; import com.intellij.openapi.util.io.ByteSequence; +import com.intellij.psi.PsiDocumentManager; +import com.intellij.psi.PsiFile; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.*; import com.intellij.util.io.*; @@ -50,6 +54,7 @@ public class MapReduceIndex<Key, Value, Input> implements UpdatableIndex<Key,Val private final DataExternalizer<Value> myValueExternalizer; private final DataExternalizer<Collection<Key>> mySnapshotIndexExternalizer; + private final boolean myIsPsiBackedIndex; private PersistentHashMap<Integer, Collection<Key>> myInputsIndex; private PersistentHashMap<Integer, ByteSequence> myContents; @@ -75,14 +80,16 @@ public class MapReduceIndex<Key, Value, Input> implements UpdatableIndex<Key,Val public MapReduceIndex(@Nullable final ID<Key, Value> indexId, DataIndexer<Key, Value, Input> indexer, @NotNull IndexStorage<Key, Value> storage) throws IOException { - this(indexId, indexer, storage, null, null); + this(indexId, indexer, storage, null, null, false); } public MapReduceIndex(@Nullable final ID<Key, Value> indexId, DataIndexer<Key, Value, Input> indexer, @NotNull IndexStorage<Key, Value> storage, DataExternalizer<Collection<Key>> snapshotIndexExternalizer, - DataExternalizer<Value> valueDataExternalizer) throws IOException { + DataExternalizer<Value> valueDataExternalizer, + boolean psiBasedIndex + ) throws IOException { myIndexId = indexId; myIndexer = indexer; myStorage = storage; @@ -91,6 +98,7 @@ public class MapReduceIndex<Key, Value, Input> implements UpdatableIndex<Key,Val mySnapshotIndexExternalizer = snapshotIndexExternalizer; myValueExternalizer = valueDataExternalizer; myContents = createContentsIndex(); + myIsPsiBackedIndex = psiBasedIndex; } private PersistentHashMap<Integer, ByteSequence> createContentsIndex() throws IOException { @@ -557,7 +565,34 @@ public class MapReduceIndex<Key, Value, Input> implements UpdatableIndex<Key,Val return result; } - private static Integer getHashOfContent(FileContent content) throws IOException { + private Integer getHashOfContent(FileContent content) throws IOException { + if (myIsPsiBackedIndex && myHasSnapshotMapping && content instanceof FileContentImpl) { + // psi backed index should use existing psi to build index value (FileContentImpl.getPsiFileAccountingForUnsavedDocument()) + // so we should use different bytes to calculate hash(Id) + Integer previouslyCalculatedUncommittedHashId = content.getUserData(ourSavedUncommittedHashIdKey); + + if (previouslyCalculatedUncommittedHashId == null) { + Document document = FileDocumentManager.getInstance().getCachedDocument(content.getFile()); + + if (document != null) { // if document is not committed + PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(content.getProject()); + + if (psiDocumentManager.isUncommited(document)) { + PsiFile file = psiDocumentManager.getCachedPsiFile(document); + Charset charset = ((FileContentImpl)content).getCharset(); + + if (file != null) { + previouslyCalculatedUncommittedHashId = ContentHashesSupport + .calcContentHashIdWithFileType(file.getText().getBytes(charset), charset, + content.getFileType()); + content.putUserData(ourSavedUncommittedHashIdKey, previouslyCalculatedUncommittedHashId); + } + } + } + } + if (previouslyCalculatedUncommittedHashId != null) return previouslyCalculatedUncommittedHashId; + } + Integer previouslyCalculatedContentHashId = content.getUserData(ourSavedContentHashIdKey); if (previouslyCalculatedContentHashId == null) { byte[] hash = content instanceof FileContentImpl ? ((FileContentImpl)content).getHash():null; @@ -616,6 +651,7 @@ public class MapReduceIndex<Key, Value, Input> implements UpdatableIndex<Key,Val } private static final com.intellij.openapi.util.Key<Integer> ourSavedContentHashIdKey = com.intellij.openapi.util.Key.create("saved.content.hash.id"); + private static final com.intellij.openapi.util.Key<Integer> ourSavedUncommittedHashIdKey = com.intellij.openapi.util.Key.create("saved.uncommitted.hash.id"); protected void updateWithMap(final int inputId, int savedInputId, @NotNull Map<Key, Value> newData, |