<?xml version="1.0" encoding="UTF-8"?>
<module relativePaths="true" type="JAVA_MODULE" version="4">
- <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_3" inherit-compiler-output="true">
+ <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_4" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
myComponentId = componentId;
}
+ public CodeGenerationException(final String componentId, final String message, final Throwable cause) {
+ super(message, cause);
+ myComponentId = componentId;
+ }
+
public String getComponentId() {
return myComponentId;
}
rootContainer = nestedFormLoader.loadForm(formName);
}
catch (Exception e) {
- throw new CodeGenerationException(null, "Error loading nested form: " + e.getMessage());
+ throw new CodeGenerationException(null, "Error loading nested form: " + e.getMessage(), e);
}
final Set thisFormNestedForms = new HashSet();
final CodeGenerationException[] validateExceptions = new CodeGenerationException[1];
}
finally {
compileContext.commitZipFiles(); // just to be on the safe side; normally should do nothing if called in isUpToDate()
+ CompilerCacheManager.getInstance(myProject).flushCaches();
}
}
}, null);
compileContext.getMessageCount(CompilerMessageCategory.WARNING),
finish - start
);
+ CompilerCacheManager.getInstance(myProject).flushCaches();
//if (LOG.isDebugEnabled()) {
// LOG.debug("COMPILATION FINISHED");
//}
finally {
// drop in case it has not been dropped yet.
dropDependencyCache(context);
-
final VirtualFile[] allOutputDirs = context.getAllOutputDirectories();
if (didSomething && GENERATE_CLASSPATH_INDEX) {
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.LowMemoryWatcher;
-import com.intellij.openapi.util.ShutDownTracker;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
private final Map<GenericCompiler<?,?,?>, GenericCompilerCache<?,?,?>> myGenericCachesMap = new HashMap<GenericCompiler<?,?,?>, GenericCompilerCache<?,?,?>>();
private final List<Disposable> myCacheDisposables = new ArrayList<Disposable>();
private final File myCachesRoot;
- private LowMemoryWatcher myMemWatcher;
-
- private final Runnable myShutdownTask = new Runnable() {
- public void run() {
- flushCaches();
- }
- };
-
private final Project myProject;
public CompilerCacheManager(Project project) {
}
public void projectOpened() {
- myMemWatcher = LowMemoryWatcher.register(new LowMemoryWatcher.ForceableAdapter() {
- public void force() {
- flushCaches();
- }
- });
- ShutDownTracker.getInstance().registerShutdownTask(myShutdownTask);
}
public void projectClosed() {
- myMemWatcher.stop();
- ShutDownTracker.getInstance().unregisterShutdownTask(myShutdownTask);
- flushCaches();
}
@NotNull
final String outputPath = artifact.getOutputPath();
return !StringUtil.isEmpty(outputPath) && artifact.getRootElement() instanceof ArtifactRootElement<?>;
}
+
+ public static Set<Module> getModulesIncludedInArtifacts(final @NotNull Collection<? extends Artifact> artifacts, final @NotNull Project project) {
+ final Set<Module> modules = new HashSet<Module>();
+ final PackagingElementResolvingContext resolvingContext = ArtifactManager.getInstance(project).getResolvingContext();
+ for (Artifact artifact : artifacts) {
+ processPackagingElements(artifact, ModuleOutputElementType.MODULE_OUTPUT_ELEMENT_TYPE, new Processor<ModuleOutputPackagingElement>() {
+ @Override
+ public boolean process(ModuleOutputPackagingElement moduleOutputPackagingElement) {
+ ContainerUtil.addIfNotNull(modules, moduleOutputPackagingElement.findModule(resolvingContext));
+ return true;
+ }
+ }, resolvingContext, true);
+ }
+ return modules;
+ }
}
}
public static ModuleCompileScope createScopeForModulesInArtifacts(@NotNull Project project, @NotNull Collection<? extends Artifact> artifacts) {
- final Set<Module> modules = new HashSet<Module>();
- final PackagingElementResolvingContext context = ArtifactManager.getInstance(project).getResolvingContext();
- for (Artifact artifact : artifacts) {
- ArtifactUtil.processPackagingElements(artifact, ModuleOutputElementType.MODULE_OUTPUT_ELEMENT_TYPE, new Processor<ModuleOutputPackagingElement>() {
- public boolean process(ModuleOutputPackagingElement moduleOutputPackagingElement) {
- final Module module = moduleOutputPackagingElement.findModule(context);
- if (module != null) {
- modules.add(module);
- }
- return true;
- }
- }, context, true);
- }
-
+ final Set<Module> modules = ArtifactUtil.getModulesIncludedInArtifacts(artifacts, project);
return new ModuleCompileScope(project, modules.toArray(new Module[modules.size()]), true);
}
}
@Override
- public void visitNewExpression(PsiNewExpression expression) {
+ public void visitNewExpression(final PsiNewExpression expression) {
PsiType expressionPsiType = expression.getType();
if (expressionPsiType instanceof PsiArrayType) {
Evaluator dimensionEvaluator = null;
initializerEvaluator
);
}
- else { // must be a class ref
- LOG.assertTrue(expressionPsiType instanceof PsiClassType);
+ else if (expressionPsiType instanceof PsiClassType){ // must be a class ref
PsiClass aClass = ((PsiClassType)expressionPsiType).resolve();
if(aClass instanceof PsiAnonymousClass) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.anonymous.class.evaluation.not.supported"));
argumentEvaluators
);
}
+ else {
+ if (expressionPsiType != null) {
+ throwEvaluateException("Unsupported expression type: " + expressionPsiType.getPresentableText());
+ }
+ else {
+ throwEvaluateException("Unknown type for expression: " + expression.getText());
+ }
+ }
}
@Override
import com.intellij.debugger.jdi.ThreadReferenceProxyImpl;
import com.intellij.debugger.requests.ClassPrepareRequestor;
import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.psi.PsiClass;
import com.sun.jdi.event.LocatableEvent;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.List;
public abstract class Breakpoint extends FilteredRequestor implements ClassPrepareRequestor {
- private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.ui.breakpoints.Breakpoint");
-
public boolean ENABLED = true;
public boolean LOG_ENABLED = false;
public boolean LOG_EXPRESSION_ENABLED = false;
}
protected void createOrWaitPrepare(final DebugProcessImpl debugProcess, final SourcePosition classPosition) {
- debugProcess.getRequestsManager().callbackOnPrepareClasses(Breakpoint.this, classPosition);
+ debugProcess.getRequestsManager().callbackOnPrepareClasses(this, classPosition);
List list = debugProcess.getPositionManager().getAllClasses(classPosition);
for (final Object aList : list) {
return false;
}
- final String[] title = new String[] {DebuggerBundle.message("title.error.evaluating.breakpoint.condition") };
+ final String[] title = {DebuggerBundle.message("title.error.evaluating.breakpoint.condition") };
try {
final StackFrameProxyImpl frameProxy = context.getThread().frame(0);
updateUI(EmptyRunnable.getInstance());
}
- public void updateUI(final Runnable afterUpdate) {
+ public void updateUI(@NotNull Runnable afterUpdate) {
}
public void delete() {
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.FixedSizeButton;
import com.intellij.openapi.util.Key;
+import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.ui.FieldPanel;
private JButton myMakeDefaultButton;
ButtonGroup mySuspendPolicyGroup;
- public static final @NonNls String CONTROL_LOG_MESSAGE = "logMessage";
+ @NonNls public static final String CONTROL_LOG_MESSAGE = "logMessage";
private BreakpointComboboxHandler myBreakpointComboboxHandler;
private static final int MAX_COMBO_WIDTH = 300;
private final FixedSizeButton myConditionMagnifierButton;
public void actionPerformed(ActionEvent e) {
reloadClassFilters();
- ClassFilter classFilter;
- classFilter = createClassConditionFilter();
+ ClassFilter classFilter = createClassConditionFilter();
EditClassFiltersDialog _dialog = new EditClassFiltersDialog(myProject, classFilter);
_dialog.setFilters(myClassFilters, myClassExclusionFilters);
*/
public void initFrom(Breakpoint breakpoint) {
myBreakpointComboboxHandler.initFrom(breakpoint);
- myPassCountField.setText((breakpoint.COUNT_FILTER > 0)? Integer.toString(breakpoint.COUNT_FILTER) : "");
+ myPassCountField.setText(breakpoint.COUNT_FILTER > 0 ? Integer.toString(breakpoint.COUNT_FILTER) : "");
PsiElement context = breakpoint.getEvaluationElement();
myPassCountCheckbox.setSelected(breakpoint.COUNT_FILTER_ENABLED);
/**
* Save values in the UI components to the breakpoint object
*/
- public void saveTo(Breakpoint breakpoint, Runnable afterUpdate) {
+ public void saveTo(Breakpoint breakpoint, @NotNull Runnable afterUpdate) {
myBreakpointComboboxHandler.saveTo(breakpoint, myLeaveEnabledRadioButton.isSelected());
try {
String text = myPassCountField.getText().trim();
}
catch (Exception e) {
}
- breakpoint.COUNT_FILTER_ENABLED = breakpoint.COUNT_FILTER > 0? myPassCountCheckbox.isSelected() : false;
+ breakpoint.COUNT_FILTER_ENABLED = breakpoint.COUNT_FILTER > 0 && myPassCountCheckbox.isSelected();
breakpoint.setCondition(myConditionCombo.getText());
- breakpoint.CONDITION_ENABLED = !breakpoint.getCondition().isEmpty() ? myConditionCheckbox.isSelected() : false;
+ breakpoint.CONDITION_ENABLED = !breakpoint.getCondition().isEmpty() && myConditionCheckbox.isSelected();
breakpoint.setLogMessage(myLogExpressionCombo.getText());
- breakpoint.LOG_EXPRESSION_ENABLED = !breakpoint.getLogMessage().isEmpty()? myLogExpressionCheckBox.isSelected() : false;
+ breakpoint.LOG_EXPRESSION_ENABLED = !breakpoint.getLogMessage().isEmpty() && myLogExpressionCheckBox.isSelected();
breakpoint.LOG_ENABLED = myLogMessageCheckBox.isSelected();
breakpoint.SUSPEND_POLICY = getSelectedSuspendPolicy();
reloadInstanceFilters();
updateInstanceFilterEditor(true);
updateClassFilterEditor(true);
- breakpoint.INSTANCE_FILTERS_ENABLED = myInstanceFiltersField.getText().length() > 0 ? myInstanceFiltersCheckBox.isSelected() : false;
- breakpoint.CLASS_FILTERS_ENABLED = myClassFiltersField.getText().length() > 0 ? myClassFiltersCheckBox.isSelected() : false;
+ breakpoint.INSTANCE_FILTERS_ENABLED = myInstanceFiltersField.getText().length() > 0 && myInstanceFiltersCheckBox.isSelected();
+ breakpoint.CLASS_FILTERS_ENABLED = myClassFiltersField.getText().length() > 0 && myClassFiltersCheckBox.isSelected();
breakpoint.setClassFilters(myClassFilters);
breakpoint.setClassExclusionFilters(myClassExclusionFilters);
breakpoint.setInstanceFilters(myInstanceFilters);
breakpoint.updateUI(afterUpdate);
}
- private String concatWith(List<String> s, String concator) {
- String result = "";
- for (Iterator iterator = s.iterator(); iterator.hasNext();) {
- String str = (String) iterator.next();
- result += str + concator;
- }
- if (result.length() > 0) {
- return result.substring(0, result.length() - concator.length());
- }
- else {
- return "";
- }
+ private static String concatWith(List<String> s, String concator) {
+ return StringUtil.join(s, concator);
}
- private String concatWithEx(List<String> s, String concator, int N, String NthConcator) {
+ private static String concatWithEx(List<String> s, String concator, int N, String NthConcator) {
String result = "";
int i = 1;
for (Iterator iterator = s.iterator(); iterator.hasNext(); i++) {
private void updateInstanceFilterEditor(boolean updateText) {
List<String> filters = new ArrayList<String>();
- for (int i = 0; i < myInstanceFilters.length; i++) {
- InstanceFilter instanceFilter = myInstanceFilters[i];
- if(instanceFilter.isEnabled()) {
+ for (InstanceFilter instanceFilter : myInstanceFilters) {
+ if (instanceFilter.isEnabled()) {
filters.add(Long.toString(instanceFilter.getId()));
}
}
}
}
}
- for (int i = 0; i < myInstanceFilters.length; i++) {
- InstanceFilter instanceFilter = myInstanceFilters[i];
- if(!instanceFilter.isEnabled()) idxs.add(instanceFilter);
+ for (InstanceFilter instanceFilter : myInstanceFilters) {
+ if (!instanceFilter.isEnabled()) idxs.add(instanceFilter);
}
myInstanceFilters = idxs.toArray(new InstanceFilter[idxs.size()]);
}
private void updateClassFilterEditor(boolean updateText) {
List<String> filters = new ArrayList<String>();
- for (int i = 0; i < myClassFilters.length; i++) {
- com.intellij.ui.classFilter.ClassFilter classFilter = myClassFilters[i];
- if(classFilter.isEnabled()) {
+ for (com.intellij.ui.classFilter.ClassFilter classFilter : myClassFilters) {
+ if (classFilter.isEnabled()) {
filters.add(classFilter.getPattern());
}
}
List<String> excludeFilters = new ArrayList<String>();
- for (int i = 0; i < myClassExclusionFilters.length; i++) {
- com.intellij.ui.classFilter.ClassFilter classFilter = myClassExclusionFilters[i];
- if(classFilter.isEnabled()) {
+ for (com.intellij.ui.classFilter.ClassFilter classFilter : myClassExclusionFilters) {
+ if (classFilter.isEnabled()) {
excludeFilters.add("-" + classFilter.getPattern());
}
}
if (updateText) {
String editorText = concatWith(filters, " ");
- if(filters.size() > 0) editorText += " ";
+ if(!filters.isEmpty()) editorText += " ";
editorText += concatWith(excludeFilters, " ");
myClassFiltersField.setText(editorText);
}
int width = (int)Math.sqrt(myClassExclusionFilters.length + myClassFilters.length) + 1;
String tipText = concatWithEx(filters, " ", width, "\n");
- if(filters.size() > 0) tipText += "\n";
+ if(!filters.isEmpty()) tipText += "\n";
tipText += concatWithEx(excludeFilters, " ", width, "\n");
myClassFiltersField.getTextField().setToolTipText(tipText);
}
}
}
- for (int i = 0; i < myClassFilters.length; i++) {
- com.intellij.ui.classFilter.ClassFilter classFilter = myClassFilters[i];
- if(!classFilter.isEnabled()) classFilters.add(classFilter);
+ for (com.intellij.ui.classFilter.ClassFilter classFilter : myClassFilters) {
+ if (!classFilter.isEnabled()) classFilters.add(classFilter);
}
- for (int i = 0; i < myClassExclusionFilters.length; i++) {
- com.intellij.ui.classFilter.ClassFilter classFilter = myClassExclusionFilters[i];
- if(!classFilter.isEnabled()) exclusionFilters.add(classFilter);
+ for (com.intellij.ui.classFilter.ClassFilter classFilter : myClassExclusionFilters) {
+ if (!classFilter.isEnabled()) exclusionFilters.add(classFilter);
}
myClassFilters = classFilters .toArray(new com.intellij.ui.classFilter.ClassFilter[classFilters .size()]);
myClassExclusionFilters = exclusionFilters.toArray(new com.intellij.ui.classFilter.ClassFilter[exclusionFilters.size()]);
public void setEnabled(boolean enabled) {
myPanel.setEnabled(enabled);
Component[] components = myPanel.getComponents();
- for (int i = 0; i < components.length; i++) {
- Component component = components[i];
+ for (Component component : components) {
component.setEnabled(enabled);
}
}
protected void updateCheckboxes() {
- JCheckBox [] checkBoxes = new JCheckBox[] { myConditionCheckbox, myInstanceFiltersCheckBox, myClassFiltersCheckBox};
+ JCheckBox [] checkBoxes = { myConditionCheckbox, myInstanceFiltersCheckBox, myClassFiltersCheckBox };
JCheckBox selected = null;
- for(int i =0; i < checkBoxes.length; i++) {
- if(checkBoxes[i].isSelected()) {
- selected = checkBoxes[i];
+ for (JCheckBox checkBoxe : checkBoxes) {
+ if (checkBoxe.isSelected()) {
+ selected = checkBoxe;
break;
}
}
myPassCountCheckbox.setEnabled(true);
}
- for(int i =0; i < checkBoxes.length; i++) {
- checkBoxes[i].setEnabled (!myPassCountCheckbox.isSelected());
+ for (JCheckBox checkBoxe : checkBoxes) {
+ checkBoxe.setEnabled(!myPassCountCheckbox.isSelected());
}
myPassCountField.setEditable(myPassCountCheckbox.isSelected());
}
public void selectBreakpoint(Breakpoint breakpoint) {
- for (int idx = 0; idx < myItems.length; idx++) {
- final ComboboxItem item = myItems[idx];
- if (breakpoint == null? item.getBreakpoint() == null : breakpoint.equals(item.getBreakpoint())) {
+ for (final ComboboxItem item : myItems) {
+ if (breakpoint == null ? item.getBreakpoint() == null : breakpoint.equals(item.getBreakpoint())) {
if (!item.equals(getSelectedItem())) {
setSelectedItem(item);
}
}
public int hashCode() {
- return (breakpoint != null ? breakpoint.hashCode() : 0);
+ return breakpoint != null ? breakpoint.hashCode() : 0;
}
}
setText(text);
final Icon icon;
if (breakpoint != null) {
- icon = (breakpoint instanceof BreakpointWithHighlighter)?
- breakpoint.ENABLED? ((BreakpointWithHighlighter)breakpoint).getSetIcon(false) : ((BreakpointWithHighlighter)breakpoint).getDisabledIcon(false) : breakpoint.getIcon();
+ icon = breakpoint instanceof BreakpointWithHighlighter ?
+ breakpoint.ENABLED? ((BreakpointWithHighlighter)breakpoint).getSetIcon(false) : ((BreakpointWithHighlighter)breakpoint)
+ .getDisabledIcon(false) : breakpoint.getIcon();
}
else {
icon = null;
private SourcePosition mySourcePosition;
private boolean myVisible = true;
- private Icon myIcon = getSetIcon(false);
+ private volatile Icon myIcon = getSetIcon(false);
@Nullable private String myClassName;
@Nullable private String myPackageName;
@Nullable private String myInvalidMessage;
/**
* updates the state of breakpoint and all the related UI widgets etc
*/
- public final void updateUI(final Runnable afterUpdate) {
+ public final void updateUI(@NotNull final Runnable afterUpdate) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
return;
}
private void updateGutter() {
if(myVisible) {
- if (getHighlighter() != null && getHighlighter().isValid() && isValid()) {
- setupGutterRenderer();
+ RangeHighlighter highlighter = getHighlighter();
+ if (highlighter != null && highlighter.isValid() && isValid()) {
+ setupGutterRenderer(highlighter);
}
else {
DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().removeBreakpoint(this);
}
/**
- * called by BreakpointManeger when destroying the breakpoint
+ * called by BreakpointManager when destroying the breakpoint
*/
public void delete() {
if (isVisible()) {
});
}
- private void setupGutterRenderer() {
+ private void setupGutterRenderer(@NotNull RangeHighlighter highlighter) {
MyGutterIconRenderer renderer = new MyGutterIconRenderer(getIcon(), getDescription());
- getHighlighter().setGutterIconRenderer(renderer);
+ highlighter.setGutterIconRenderer(renderer);
}
public abstract Key<? extends BreakpointWithHighlighter> getCategory();
import com.intellij.debugger.DebuggerBundle;
import com.intellij.ide.util.ClassFilter;
import com.intellij.openapi.project.Project;
+import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
myNotifyUncaughtCheckBox.setSelected(exceptionBreakpoint.NOTIFY_UNCAUGHT);
}
- public void saveTo(Breakpoint breakpoint, Runnable afterUpdate) {
+ public void saveTo(Breakpoint breakpoint, @NotNull Runnable afterUpdate) {
ExceptionBreakpoint exceptionBreakpoint = (ExceptionBreakpoint)breakpoint;
exceptionBreakpoint.NOTIFY_CAUGHT = myNotifyCaughtCheckBox.isSelected();
exceptionBreakpoint.NOTIFY_UNCAUGHT = myNotifyUncaughtCheckBox.isSelected();
import com.intellij.debugger.DebuggerBundle;
import com.intellij.openapi.project.Project;
+import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
myWatchModificationCheckBox.setSelected(fieldBreakpoint.WATCH_MODIFICATION);
}
- public void saveTo(Breakpoint breakpoint, Runnable afterUpdate) {
+ public void saveTo(Breakpoint breakpoint, @NotNull Runnable afterUpdate) {
FieldBreakpoint fieldBreakpoint = (FieldBreakpoint)breakpoint;
fieldBreakpoint.WATCH_ACCESS = myWatchAccessCheckBox.isSelected();
import com.intellij.debugger.DebuggerBundle;
import com.intellij.openapi.project.Project;
+import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
}
}
- public void saveTo(Breakpoint breakpoint, Runnable afterUpdate) {
+ public void saveTo(Breakpoint breakpoint, @NotNull Runnable afterUpdate) {
if (breakpoint instanceof MethodBreakpoint) {
MethodBreakpoint methodBreakpoint = (MethodBreakpoint)breakpoint;
methodBreakpoint.WATCH_ENTRY = myWatchEntryCheckBox.isSelected();
public interface PositionManager {
@Nullable
- SourcePosition getSourcePosition(Location location) throws NoDataException;
+ SourcePosition getSourcePosition(@Nullable Location location) throws NoDataException;
@NotNull
List<ReferenceType> getAllClasses(SourcePosition classPosition) throws NoDataException;
@Override
protected RunnerAndConfigurationSettings createConfigurationByElement(Location location, ConfigurationContext context) {
location = JavaExecutionUtil.stepIntoSingleClass(location);
+ if (location == null) return null;
final Project project = location.getProject();
final PsiElement element = location.getPsiElement();
myPsiClass = getAppletClass(element, PsiManager.getInstance(project));
import com.intellij.util.containers.Convertor;
import junit.runner.BaseTestRunner;
import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.Nullable;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
return false;
}
+ @Nullable
+ protected static PsiMethod findFirstTestMethod(PsiClass clazz) {
+ PsiMethod testMethod = null;
+ for (PsiMethod method : clazz.getMethods()) {
+ if (isTestMethod(MethodLocation.elementInClass(method, clazz)) || isSuiteMethod(method)) {
+ testMethod = method;
+ break;
+ }
+ }
+ return testMethod;
+ }
+
public static class TestMethodFilter implements Condition<PsiMethod> {
private final PsiClass myClass;
import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.SdkProjectStructureElement;
import com.intellij.openapi.roots.ui.util.CellAppearance;
import com.intellij.openapi.roots.ui.util.OrderEntryCellAppearanceUtils;
+import com.intellij.openapi.ui.ComboBoxTableRenderer;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
JComboBox scopeEditor = new JComboBox(new EnumComboBoxModel<DependencyScope>(DependencyScope.class));
myEntryTable.setDefaultEditor(DependencyScope.class, new DefaultCellEditor(scopeEditor));
+ myEntryTable.setDefaultRenderer(DependencyScope.class, new ComboBoxTableRenderer<DependencyScope>(DependencyScope.values()) {
+ @Override
+ protected String getTextFor(@NotNull final DependencyScope value) {
+ return value.getDisplayName();
+ }
+ });
+
myEntryTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
new SpeedSearchBase<Table>(myEntryTable) {
}
}
};
- navigateAction.registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE).getShortcutSet(), myEntryTable);
+ navigateAction.registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE).getShortcutSet(),
+ myEntryTable);
actionGroup.add(navigateAction);
actionGroup.add(new MyFindUsagesAction());
PopupHandler.installPopupHandler(myEntryTable, actionGroup, ActionPlaces.UNKNOWN, ActionManager.getInstance());
final CompletionParameters classParams;
final int invocationCount = parameters.getInvocationCount();
- final int offset = parameters.getOffset();
if (empty.get().booleanValue()) {
- classParams = new CompletionParameters(position, file, CompletionType.CLASS_NAME, offset, invocationCount);
+ classParams = parameters.withType(CompletionType.CLASS_NAME);
}
else if (invocationCount > 1) {
- classParams = new CompletionParameters(position, file, CompletionType.CLASS_NAME, offset, invocationCount - 1);
+ classParams = parameters.withType(CompletionType.CLASS_NAME).withInvocationCount(invocationCount - 1);
} else {
return;
}
}
}
- public static void insertParentheses(InsertionContext context, LookupItem delegate, final PsiClass psiClass) {
+ public static boolean insertParentheses(InsertionContext context, LookupItem delegate, final PsiClass psiClass) {
final PsiElement place = context.getFile().findElementAt(context.getStartOffset());
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(context.getProject()).getResolveHelper();
assert place != null;
}
JavaCompletionUtil.insertParentheses(context, delegate, false, hasParams);
+ return hasParams;
}
private static Runnable generateAnonymousBody(final Editor editor, final PsiFile file) {
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.editor.ex.EditorEx;
-import com.intellij.openapi.editor.highlighter.HighlighterIterator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
InsertHandlerState state = new InsertHandlerState(context.getSelectionEndOffset(), context.getSelectionEndOffset());
- final boolean needLeftParenth = isToInsertParenth(context, item);
- final boolean hasParams = needLeftParenth && hasParams(context, item);
-
if (CompletionUtil.isOverwrite(item, completionChar)) {
- removeEndOfIdentifier(needLeftParenth && hasParams, context);
+ removeEndOfIdentifier(context);
}
else if(context.getOffsetMap().getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET) != context.getSelectionEndOffset()) {
JavaCompletionUtil.resetParensInfo(context.getOffsetMap());
}
- handleParentheses(hasParams, needLeftParenth, tailType, context, state);
+ handleParentheses(false, false, tailType, context, state);
handleBrackets(item, document, state);
if (item.getObject() instanceof PsiVariable) {
qualifyIfNeeded(context, item);
- if (needLeftParenth && hasParams){
- // Invoke parameters popup
- AutoPopupController.getInstance(project).autoPopupParameterInfo(editor, null);
- }
-
- if (tailType == TailType.DOT && !(item.getObject() instanceof PsiClass)) {
+ if (tailType == TailType.DOT) {
AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null);
}
- if (completionChar == '#') {
- context.setLaterRunnable(new Runnable() {
- public void run() {
- new CodeCompletionHandlerBase(CompletionType.BASIC).invoke(project, editor, file);
- }
- });
- }
-
- if (insertingAnnotation(context, item)) {
- // Check if someone inserts annotation class that require @
- PsiElement elementAt = file.findElementAt(context.getStartOffset());
- final PsiElement parentElement = elementAt != null ? elementAt.getParent():null;
-
- if (elementAt instanceof PsiIdentifier &&
- (PsiTreeUtil.getParentOfType(elementAt, PsiAnnotationParameterList.class) != null ||
- parentElement instanceof PsiErrorElement && parentElement.getParent() instanceof PsiJavaFile // top level annotation without @
- )
- && isAtTokenNeeded(context)) {
- int expectedOffsetForAtToken = elementAt.getTextRange().getStartOffset();
- document.insertString(expectedOffsetForAtToken, "@");
- }
- }
}
private static void qualifyIfNeeded(InsertionContext context, LookupElement item) {
}
}
- private static boolean isAtTokenNeeded(InsertionContext myContext) {
- HighlighterIterator iterator = ((EditorEx)myContext.getEditor()).getHighlighter().createIterator(myContext.getStartOffset());
- LOG.assertTrue(iterator.getTokenType() == JavaTokenType.IDENTIFIER);
- iterator.retreat();
- if (iterator.getTokenType() == TokenType.WHITE_SPACE) iterator.retreat();
- return iterator.getTokenType() != JavaTokenType.AT && iterator.getTokenType() != JavaTokenType.DOT;
- }
-
private static void handleBrackets(LookupElement item, Document document, InsertHandlerState myState){
// brackets
final Integer bracketsAttr = (Integer)item.getUserData(LookupItem.BRACKETS_COUNT_ATTR);
}
}
- protected static boolean isToInsertParenth(InsertionContext context, LookupElement item){
- return insertingAnnotationWithParameters(context, item);
- }
-
- private static boolean hasParams(InsertionContext context, LookupElement item){
- final String lookupString = item.getLookupString();
- if (PsiKeyword.SYNCHRONIZED.equals(lookupString)) {
- final PsiElement place = context.getFile().findElementAt(context.getStartOffset());
- return PsiTreeUtil.getParentOfType(place, PsiMember.class, PsiCodeBlock.class) instanceof PsiCodeBlock;
- }
- else if(PsiKeyword.CATCH.equals(lookupString) ||
- PsiKeyword.SWITCH.equals(lookupString) ||
- PsiKeyword.WHILE.equals(lookupString) ||
- PsiKeyword.FOR.equals(lookupString))
- return true;
- else if (insertingAnnotationWithParameters(context, item)) {
- return true;
- }
- return false;
- }
-
- private static boolean insertingAnnotationWithParameters(InsertionContext context, LookupElement item) {
- if(insertingAnnotation(context, item)) {
- final Document document = context.getEditor().getDocument();
- PsiDocumentManager.getInstance(context.getProject()).commitDocument(document);
- PsiElement elementAt = context.getFile().findElementAt(context.getStartOffset());
- if (elementAt instanceof PsiIdentifier) {
- final PsiModifierListOwner parent = PsiTreeUtil.getParentOfType(elementAt, PsiModifierListOwner.class, false, PsiCodeBlock.class);
- if (parent != null) {
- for (PsiMethod m : ((PsiClass)item.getObject()).getMethods()) {
- if (!(m instanceof PsiAnnotationMethod)) continue;
- final PsiAnnotationMemberValue defaultValue = ((PsiAnnotationMethod)m).getDefaultValue();
- if (defaultValue == null) return true;
- }
- }
- }
- }
- return false;
- }
-
- private static boolean insertingAnnotation(InsertionContext context, LookupElement item) {
- final Object obj = item.getObject();
- if (!(obj instanceof PsiClass) || !((PsiClass)obj).isAnnotationType()) return false;
-
- final Document document = context.getEditor().getDocument();
- PsiDocumentManager.getInstance(context.getProject()).commitDocument(document);
- final int offset = context.getStartOffset();
-
- final PsiFile file = context.getFile();
-
- if (PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiImportStatement.class, false) != null) return false;
-
- //outside of any class: we are surely inserting an annotation
- if (PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiClass.class, false) == null) return true;
-
- //the easiest check that there's a @ before the identifier
- return PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiAnnotation.class, false) != null;
-
- }
-
- protected static void removeEndOfIdentifier(boolean needParenth, InsertionContext context){
+ private static void removeEndOfIdentifier(InsertionContext context){
final Document document = context.getEditor().getDocument();
JavaCompletionUtil.initOffsets(context.getFile(), context.getProject(), context.getOffsetMap());
document.deleteString(context.getSelectionEndOffset(), context.getOffsetMap().getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET));
- if(context.getOffsetMap().getOffset(JavaCompletionUtil.LPAREN_OFFSET) > 0 && !needParenth){
+ if(context.getOffsetMap().getOffset(JavaCompletionUtil.LPAREN_OFFSET) > 0){
document.deleteString(context.getOffsetMap().getOffset(JavaCompletionUtil.LPAREN_OFFSET),
context.getOffsetMap().getOffset(JavaCompletionUtil.ARG_LIST_END_OFFSET));
JavaCompletionUtil.resetParensInfo(context.getOffsetMap());
case ':': return TailType.CASE_COLON; //?
case '<':
case '>':
- case '#':
case '\"':
case '[': return TailType.createSimpleTailType(completionChar);
}
--- /dev/null
+/*
+ * 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.codeInsight.completion;
+
+import com.intellij.psi.javadoc.PsiDocTag;
+import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.util.ThreeState;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * @author peter
+ */
+public class FocusInJavadoc extends CompletionConfidence {
+ @NotNull
+ @Override
+ public ThreeState shouldFocusLookup(@NotNull CompletionParameters parameters) {
+ if (PsiTreeUtil.getParentOfType(parameters.getPosition(), PsiDocTag.class) != null) {
+ return ThreeState.YES;
+ }
+ return ThreeState.UNSURE;
+ }
+}
import com.intellij.psi.*;
import com.intellij.psi.filters.ClassFilter;
import com.intellij.psi.filters.ElementFilter;
-import com.intellij.psi.filters.FilterPositionUtil;
import com.intellij.psi.filters.TrueFilter;
import com.intellij.psi.filters.classes.ThisOrAnyInnerFilter;
import com.intellij.psi.filters.element.ExcludeDeclaredFilter;
psiElement(PsiReferenceList.class).withParent(PsiTypeParameter.class));
private static final PsiJavaElementPattern.Capture<PsiElement> INSIDE_METHOD_THROWS_CLAUSE = psiElement().afterLeaf(PsiKeyword.THROWS, ",").inside(
PsiMethod.class).andNot(psiElement().inside(PsiCodeBlock.class)).andNot(psiElement().inside(PsiParameterList.class));
- private static final InsertHandler<JavaPsiClassReferenceElement> JAVA_CLASS_INSERT_HANDLER = new InsertHandler<JavaPsiClassReferenceElement>() {
- public void handleInsert(final InsertionContext context, final JavaPsiClassReferenceElement item) {
- context.setAddCompletionChar(false);
- int offset = context.getTailOffset() - 1;
- final PsiFile file = context.getFile();
- if (PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiImportStatementBase.class, false) != null) {
- final PsiJavaCodeReferenceElement ref = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiJavaCodeReferenceElement.class, false);
- final String qname = item.getQualifiedName();
- if (qname != null && (ref == null || !qname.equals(ref.getCanonicalText()))) {
- AllClassesGetter.INSERT_FQN.handleInsert(context, item);
- }
- return;
- }
-
- if (completingRawConstructor(context, item) && !JavaCompletionUtil.hasAccessibleInnerClass(item.getObject(), file)) {
- ConstructorInsertHandler.insertParentheses(context, item, item.getObject());
- DefaultInsertHandler.addImportForItem(context.getFile(), context.getStartOffset(), item);
- } else {
- new DefaultInsertHandler().handleInsert(context, item);
- }
- }
-
- private boolean completingRawConstructor(InsertionContext context, JavaPsiClassReferenceElement item) {
- final PsiJavaCodeReferenceElement ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiJavaCodeReferenceElement.class, false);
- final PsiElement prevElement = FilterPositionUtil.searchNonSpaceNonCommentBack(ref);
- if (prevElement != null && prevElement.getParent() instanceof PsiNewExpression) {
- PsiTypeParameter[] typeParameters = item.getObject().getTypeParameters();
- for (ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes((PsiExpression) prevElement.getParent(), true)) {
- final PsiType type = info.getType();
-
- if (info.isArrayTypeInfo()) {
- return false;
- }
- if (typeParameters.length > 0 && type instanceof PsiClassType && !((PsiClassType)type).isRaw()) {
- return false;
- }
- }
- return true;
- }
-
- return false;
- }
- };
public JavaClassNameCompletionContributor() {
extend(CompletionType.CLASS_NAME, psiElement(), new CompletionProvider<CompletionParameters>() {
}
public static JavaPsiClassReferenceElement createClassLookupItem(final PsiClass psiClass, final boolean inJavaContext) {
- return AllClassesGetter.createLookupItem(psiClass, inJavaContext ? JAVA_CLASS_INSERT_HANDLER : AllClassesGetter.TRY_SHORTENING);
+ return AllClassesGetter.createLookupItem(psiClass, inJavaContext ? JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER : AllClassesGetter.TRY_SHORTENING);
}
@Override
--- /dev/null
+/*
+ * 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.codeInsight.completion;
+
+import com.intellij.codeInsight.AutoPopupController;
+import com.intellij.codeInsight.ExpectedTypeInfo;
+import com.intellij.codeInsight.ExpectedTypesProvider;
+import com.intellij.codeInsight.lookup.LookupElement;
+import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.ex.EditorEx;
+import com.intellij.openapi.editor.highlighter.HighlighterIterator;
+import com.intellij.openapi.project.Project;
+import com.intellij.psi.*;
+import com.intellij.psi.filters.FilterPositionUtil;
+import com.intellij.psi.javadoc.PsiDocTag;
+import com.intellij.psi.util.PsiTreeUtil;
+
+/**
+* @author peter
+*/
+class JavaClassNameInsertHandler implements InsertHandler<JavaPsiClassReferenceElement> {
+ private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.JavaClassNameInsertHandler");
+ static final InsertHandler<JavaPsiClassReferenceElement> JAVA_CLASS_INSERT_HANDLER = new JavaClassNameInsertHandler();
+
+ public void handleInsert(final InsertionContext context, final JavaPsiClassReferenceElement item) {
+ final char c = context.getCompletionChar();
+
+ if (c != '.' && c != ' ' && c != '#') {
+ context.setAddCompletionChar(false);
+ }
+
+ int offset = context.getTailOffset() - 1;
+ final PsiFile file = context.getFile();
+ if (PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiImportStatementBase.class, false) != null) {
+ final PsiJavaCodeReferenceElement ref = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiJavaCodeReferenceElement.class, false);
+ final String qname = item.getQualifiedName();
+ if (qname != null && (ref == null || !qname.equals(ref.getCanonicalText()))) {
+ AllClassesGetter.INSERT_FQN.handleInsert(context, item);
+ }
+ return;
+ }
+
+ PsiElement position = file.findElementAt(offset);
+ PsiClass psiClass = item.getObject();
+ final Project project = context.getProject();
+ final boolean annotation = insertingAnnotation(context, item);
+
+ final Editor editor = context.getEditor();
+ if (c == '#') {
+ context.setLaterRunnable(new Runnable() {
+ public void run() {
+ new CodeCompletionHandlerBase(CompletionType.BASIC).invoke(project, editor, file);
+ }
+ });
+ }
+
+ if (position != null) {
+ PsiElement parent = position.getParent();
+ if (parent instanceof PsiJavaCodeReferenceElement) {
+ final PsiJavaCodeReferenceElement ref = (PsiJavaCodeReferenceElement)parent;
+ if (PsiTreeUtil.getParentOfType(position, PsiDocTag.class) != null) {
+ if (ref.isReferenceTo(psiClass)) {
+ return;
+ }
+ }
+ final PsiReferenceParameterList parameterList = ref.getParameterList();
+ if (parameterList != null && parameterList.getTextLength() > 0) {
+ return;
+ }
+ }
+ }
+
+ if (completingRawConstructor(context, item) && !JavaCompletionUtil.hasAccessibleInnerClass(psiClass, file)) {
+ if (ConstructorInsertHandler.insertParentheses(context, item, psiClass)) {
+ AutoPopupController.getInstance(project).autoPopupParameterInfo(editor, null);
+ }
+ }
+ else if (insertingAnnotationWithParameters(context, item)) {
+ JavaCompletionUtil.insertParentheses(context, item, false, true);
+ AutoPopupController.getInstance(project).autoPopupParameterInfo(editor, null);
+ }
+ DefaultInsertHandler.addImportForItem(context.getFile(), context.getStartOffset(), item);
+
+ if (annotation) {
+ // Check if someone inserts annotation class that require @
+ PsiElement elementAt = file.findElementAt(context.getStartOffset());
+ final PsiElement parentElement = elementAt != null ? elementAt.getParent():null;
+
+ if (elementAt instanceof PsiIdentifier &&
+ (PsiTreeUtil.getParentOfType(elementAt, PsiAnnotationParameterList.class) != null ||
+ parentElement instanceof PsiErrorElement && parentElement.getParent() instanceof PsiJavaFile // top level annotation without @
+ )
+ && isAtTokenNeeded(context)) {
+ int expectedOffsetForAtToken = elementAt.getTextRange().getStartOffset();
+ context.getDocument().insertString(expectedOffsetForAtToken, "@");
+ }
+ }
+
+ }
+
+ private static boolean completingRawConstructor(InsertionContext context, JavaPsiClassReferenceElement item) {
+ final PsiJavaCodeReferenceElement ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiJavaCodeReferenceElement.class, false);
+ final PsiElement prevElement = FilterPositionUtil.searchNonSpaceNonCommentBack(ref);
+ if (prevElement != null && prevElement.getParent() instanceof PsiNewExpression) {
+ PsiTypeParameter[] typeParameters = item.getObject().getTypeParameters();
+ for (ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes((PsiExpression)prevElement.getParent(), true)) {
+ final PsiType type = info.getType();
+
+ if (info.isArrayTypeInfo()) {
+ return false;
+ }
+ if (typeParameters.length > 0 && type instanceof PsiClassType && !((PsiClassType)type).isRaw()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ return false;
+ }
+
+ private static boolean insertingAnnotationWithParameters(InsertionContext context, LookupElement item) {
+ if(insertingAnnotation(context, item)) {
+ final Document document = context.getEditor().getDocument();
+ PsiDocumentManager.getInstance(context.getProject()).commitDocument(document);
+ PsiElement elementAt = context.getFile().findElementAt(context.getStartOffset());
+ if (elementAt instanceof PsiIdentifier) {
+ final PsiModifierListOwner parent = PsiTreeUtil.getParentOfType(elementAt, PsiModifierListOwner.class, false, PsiCodeBlock.class);
+ if (parent != null) {
+ for (PsiMethod m : ((PsiClass)item.getObject()).getMethods()) {
+ if (!(m instanceof PsiAnnotationMethod)) continue;
+ final PsiAnnotationMemberValue defaultValue = ((PsiAnnotationMethod)m).getDefaultValue();
+ if (defaultValue == null) return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private static boolean insertingAnnotation(InsertionContext context, LookupElement item) {
+ final Object obj = item.getObject();
+ if (!(obj instanceof PsiClass) || !((PsiClass)obj).isAnnotationType()) return false;
+
+ final Document document = context.getEditor().getDocument();
+ PsiDocumentManager.getInstance(context.getProject()).commitDocument(document);
+ final int offset = context.getStartOffset();
+
+ final PsiFile file = context.getFile();
+
+ if (PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiImportStatement.class, false) != null) return false;
+
+ //outside of any class: we are surely inserting an annotation
+ if (PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiClass.class, false) == null) return true;
+
+ //the easiest check that there's a @ before the identifier
+ return PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiAnnotation.class, false) != null;
+
+ }
+
+ private static boolean isAtTokenNeeded(InsertionContext myContext) {
+ HighlighterIterator iterator = ((EditorEx)myContext.getEditor()).getHighlighter().createIterator(myContext.getStartOffset());
+ LOG.assertTrue(iterator.getTokenType() == JavaTokenType.IDENTIFIER);
+ iterator.retreat();
+ if (iterator.getTokenType() == TokenType.WHITE_SPACE) iterator.retreat();
+ return iterator.getTokenType() != JavaTokenType.AT && iterator.getTokenType() != JavaTokenType.DOT;
+ }
+}
addKeywords(parameters, result);
if (shouldRunClassNameCompletion(result, position)) {
- result.runRemainingContributors(
- new CompletionParameters(position, parameters.getOriginalFile(), CompletionType.CLASS_NAME, parameters.getOffset(), parameters.getInvocationCount()),
+ result.runRemainingContributors(parameters.withType(CompletionType.CLASS_NAME),
new Consumer<LookupElement>() {
@Override
public void consume(LookupElement lookupElement) {
final PsiReference reference = file.findReferenceAt(selectionEndOffset);
if(reference != null) {
+ /*
if(reference instanceof PsiJavaCodeReferenceElement){
offsetMap.addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET, element.getParent().getTextRange().getEndOffset());
}
else{
- offsetMap.addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET,
- reference.getElement().getTextRange().getStartOffset() + reference.getRangeInElement().getEndOffset());
}
+ */
+ offsetMap.addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET,
+ reference.getElement().getTextRange().getStartOffset() + reference.getRangeInElement().getEndOffset());
element = file.findElementAt(offsetMap.getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET));
}
else if (isWord(element)){
+ /*
if(element instanceof PsiIdentifier && element.getParent() instanceof PsiJavaCodeReferenceElement){
offsetMap.addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET, element.getParent().getTextRange().getEndOffset());
}
else{
- offsetMap.addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET, element.getTextRange().getEndOffset());
}
+ */
+ offsetMap.addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET, element.getTextRange().getEndOffset());
element = file.findElementAt(offsetMap.getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET));
if (element == null) return;
document.insertString(exprStart, prefix + spaceWithin + ")" + spaceAfter);
CompletionUtil.emulateInsertion(context, exprStart + prefix.length(), to);
+ context.getEditor().getCaretModel().moveToOffset(context.getTailOffset());
}
}
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
/**
* @author peter
*/
public class StaticMembersWeigher extends CompletionWeigher {
public Comparable weigh(@NotNull LookupElement element, @NotNull CompletionLocation loc) {
- if (loc == null) {
- return null;
- }
if (loc.getCompletionType() != CompletionType.BASIC) return 0;
- final PsiElement position = loc.getCompletionParameters().getPosition();
-
// cheap weigher applicability goes first
final Object o = element.getObject();
if (!(o instanceof PsiMember)) return 0;
-
+
+ final PsiElement position = loc.getCompletionParameters().getPosition();
if (PsiTreeUtil.getParentOfType(position, PsiDocComment.class) != null) return 0;
if (position.getParent() instanceof PsiReferenceExpression) {
final PsiReferenceExpression refExpr = (PsiReferenceExpression)position.getParent();
if (o instanceof PsiField) return 4;
}
- if (o instanceof PsiClass && ((PsiClass) o).getContainingClass() != null) {
+ if (o instanceof PsiClass) {
+ //if (((PsiClass) o).getContainingClass() != null) return 2;
return 3;
}
import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil;
import com.intellij.codeInsight.daemon.impl.quickfix.*;
import com.intellij.codeInsight.intention.EmptyIntentionAction;
+import com.intellij.codeInsight.intention.IntentionAction;
+import com.intellij.codeInsight.intention.IntentionManager;
import com.intellij.codeInspection.InspectionProfile;
+import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection;
+import com.intellij.codeInspection.ex.GlobalInspectionToolWrapper;
import com.intellij.codeInspection.ex.InspectionManagerEx;
import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
import com.intellij.codeInspection.unusedImport.UnusedImportLocalInspection;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.PropertyKey;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Set;
+import java.util.*;
public class PostHighlightingPass extends TextEditorHighlightingPass {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.PostHighlightingPass");
private boolean myInLibrary;
private HighlightDisplayKey myDeadCodeKey;
private HighlightInfoType myDeadCodeInfoType;
+ private UnusedParametersInspection myUnusedParametersInspection;
PostHighlightingPass(@NotNull Project project,
@NotNull PsiFile file,
myDeadCodeKey = HighlightDisplayKey.find(UnusedDeclarationInspection.SHORT_NAME);
myDeadCodeInspection = (UnusedDeclarationInspection)profile.getInspectionTool(UnusedDeclarationInspection.SHORT_NAME, myFile);
myDeadCodeEnabled = profile.isToolEnabled(myDeadCodeKey, myFile);
+
+ final InspectionProfileEntry inspectionTool = profile.getInspectionTool(UnusedParametersInspection.SHORT_NAME, myFile);
+ myUnusedParametersInspection = inspectionTool != null ? (UnusedParametersInspection)((GlobalInspectionToolWrapper)inspectionTool).getTool() : null;
+ LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode() || myUnusedParametersInspection != null);
if (unusedImportEnabled && JspPsiUtil.isInJspFile(myFile)) {
final JspFile jspFile = JspPsiUtil.getJspFile(myFile);
if (jspFile != null) {
!PsiClassImplUtil.isMainMethod(method)) {
HighlightInfo highlightInfo = checkUnusedParameter(parameter, progress);
if (highlightInfo != null) {
- QuickFixAction.registerQuickFixAction(highlightInfo, new RemoveUnusedParameterFix(parameter), myUnusedSymbolKey);
+ final ArrayList<IntentionAction> options = new ArrayList<IntentionAction>();
+ options.addAll(IntentionManager.getInstance().getStandardIntentionOptions(myUnusedSymbolKey, myFile));
+ if (myUnusedParametersInspection != null) {
+ Collections.addAll(options, myUnusedParametersInspection.getSuppressActions(parameter));
+ }
+ //need suppress from Unused Parameters but settings from Unused Symbol
+ QuickFixAction.registerQuickFixAction(highlightInfo, new RemoveUnusedParameterFix(parameter),
+ options, HighlightDisplayKey.getDisplayNameByKey(myUnusedSymbolKey));
return highlightInfo;
}
}
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
-import com.intellij.refactoring.introduceVariable.PsiExpressionTrimRenderer;
+import com.intellij.psi.util.PsiExpressionTrimRenderer;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
+import com.intellij.refactoring.JavaRefactoringSettings;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
cast.getCastType().replace(factory.createTypeElement(castType));
cast.getOperand().replace(instanceOfExpression.getOperand());
PsiDeclarationStatement decl = factory.createVariableDeclarationStatement("xxx", castType, cast);
+ final Boolean createFinals = JavaRefactoringSettings.getInstance().INTRODUCE_LOCAL_CREATE_FINALS;
+ if (createFinals != null) {
+ final PsiElement[] declaredElements = decl.getDeclaredElements();
+ LOG.assertTrue(declaredElements.length == 1);
+ LOG.assertTrue(declaredElements[0] instanceof PsiLocalVariable);
+ final PsiModifierList modifierList = ((PsiLocalVariable)declaredElements[0]).getModifierList();
+ LOG.assertTrue(modifierList != null);
+ modifierList.setModifierProperty(PsiModifier.FINAL, createFinals.booleanValue());
+ }
PsiDeclarationStatement element = (PsiDeclarationStatement)insertAtAnchor(instanceOfExpression, decl);
return CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(element);
}
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
-import com.intellij.openapi.editor.ex.RangeMarkerEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.util.FieldConflictsResolver;
-import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
final Project project = targetClass.getProject();
final PsiFile targetFile = targetClass.getContainingFile();
Document document = PsiDocumentManager.getInstance(project).getDocument(targetFile);
+ if (document == null) return;
TemplateBuilderImpl builder = new TemplateBuilderImpl(method);
method = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(method);
if (method == null) return;
- assert document != null;
RangeMarker rangeMarker = document.createRangeMarker(method.getTextRange());
final Editor newEditor = positionCursor(project, targetFile, method);
Template template = builder.buildTemplate();
PsiClass baseClass = aClass.getSuperClass();
if (baseClass != null){
ArrayList<PsiMethod> array = new ArrayList<PsiMethod>();
- PsiMethod[] methods = baseClass.getMethods();
- for (PsiMethod method : methods) {
- if (method.isConstructor()) {
- if (JavaPsiFacade.getInstance(method.getProject()).getResolveHelper().isAccessible(method, aClass, aClass)) {
- array.add(method);
- }
+ for (PsiMethod method : baseClass.getConstructors()) {
+ if (JavaPsiFacade.getInstance(method.getProject()).getResolveHelper().isAccessible(method, aClass, aClass)) {
+ array.add(method);
}
}
if (!array.isEmpty()){
@NonNls private static final String HR = "<HR>";
@NonNls private static final String P = "<P>";
@NonNls private static final String DL = "<DL>";
- @NonNls private static final String H2 = "</H2>";
+ @NonNls protected static final String H2 = "</H2>";
@NonNls protected static final String HTML_CLOSE = "</HTML>";
@NonNls protected static final String HTML = "<HTML>";
@NonNls private static final String BR = "<BR>";
" background-color: #eeeeee;" +
" margin-bottom: 10px;" +
" }" +
+ " p {" +
+ " margin: 5px 0;" +
+ " }" +
" </style>" +
"</head><body>");
}
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
public class FieldAccessNotGuardedInspection extends BaseJavaLocalInspectionTool {
if (containingMethod != null && JCiPUtil.isGuardedBy(containingMethod, guard)) {
return;
}
+ if (containingMethod != null && containingMethod.isConstructor()) {
+ return;
+ }
if ("this".equals(guard)) {
if (containingMethod != null && containingMethod.hasModifierProperty(PsiModifier.SYNCHRONIZED)) {
return;
}
}
+
+ PsiElement lockExpr = findLockTryStatement(expression, guard);
+ while (lockExpr != null) {
+ PsiElement child = lockExpr;
+ while (child != null) {
+ if (isLockGuardStatement(guard, child, "lock")) return;
+ child = child.getPrevSibling();
+ }
+ lockExpr = lockExpr.getParent();
+ }
+
PsiElement check = expression;
while (true) {
final PsiSynchronizedStatement syncStatement = PsiTreeUtil.getParentOfType(check, PsiSynchronizedStatement.class);
}
check = syncStatement;
}
- //TODO: see if there is a lock via a .lock* call
myHolder.registerProblem(expression, "Access to field <code>#ref</code> outside of declared guards #loc");
}
+
+ @Nullable
+ private static PsiTryStatement findLockTryStatement(PsiReferenceExpression expression, String guard) {
+ PsiTryStatement tryStatement = PsiTreeUtil.getParentOfType(expression, PsiTryStatement.class);
+ while (tryStatement != null) {
+ PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
+ if (finallyBlock != null) {
+ for (PsiStatement psiStatement : finallyBlock.getStatements()) {
+ if (isLockGuardStatement(guard, psiStatement, "unlock")) {
+ return tryStatement;
+ }
+ }
+ }
+ tryStatement = PsiTreeUtil.getParentOfType(tryStatement, PsiTryStatement.class);
+ }
+ return tryStatement;
+ }
+
+ private static boolean isLockGuardStatement(String guard, PsiElement element, final String lockMethodStart) {
+ if (element instanceof PsiExpressionStatement) {
+ final PsiExpression psiExpression = ((PsiExpressionStatement)element).getExpression();
+ if (psiExpression instanceof PsiMethodCallExpression) {
+ final PsiReferenceExpression methodExpression = ((PsiMethodCallExpression)psiExpression).getMethodExpression();
+ final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
+ if (qualifierExpression != null && qualifierExpression.getText().equals(guard)) {
+ final PsiElement resolve = methodExpression.resolve();
+ if (resolve instanceof PsiMethod && ((PsiMethod)resolve).getName().startsWith(lockMethodStart)) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
}
}
\ No newline at end of file
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.Comparing;
-import com.intellij.openapi.util.Condition;
-import com.intellij.openapi.util.JDOMExternalizableStringList;
-import com.intellij.openapi.util.Pair;
+import com.intellij.openapi.util.*;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.AllOverridingMethodsSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.Processor;
import com.intellij.util.Query;
import com.intellij.util.containers.BidirectionalMap;
+import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
private final BidirectionalMap<Boolean, QuickFix> myQuickFixes = new BidirectionalMap<Boolean, QuickFix>();
- private final JDOMExternalizableStringList EXCLUDE_ANNOS = new JDOMExternalizableStringList();
+ public final JDOMExternalizableStringList EXCLUDE_ANNOS = new JDOMExternalizableStringList();
@NonNls private static final String QUICK_FIX_NAME = InspectionsBundle.message("inspection.empty.method.delete.quickfix");
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.emptyMethod.EmptyMethodInspection");
return SHORT_NAME;
}
+ @Override
+ public void writeSettings(Element node) throws WriteExternalException {
+ if (!EXCLUDE_ANNOS.isEmpty()) {
+ super.writeSettings(node);
+ }
+ }
+
private LocalQuickFix getFix(final ProblemDescriptionsProcessor processor, final boolean needToDeleteHierarchy) {
QuickFix fix = myQuickFixes.get(needToDeleteHierarchy);
if (fix == null) {
@SuppressWarnings({"HardCodedStringLiteral"})
public void loadState(Element element) {
Element entryPointsElement = element.getChild("entry_points");
- final String version = entryPointsElement.getAttributeValue(VERSION_ATTR);
- if (!Comparing.strEqual(version, VERSION)) {
- convert(entryPointsElement, myPersistentEntryPoints);
- }
- else {
- List content = entryPointsElement.getChildren();
- for (final Object aContent : content) {
- Element entryElement = (Element)aContent;
- if (ENTRY_POINT_ATTR.equals(entryElement.getName())) {
- SmartRefElementPointerImpl entryPoint = new SmartRefElementPointerImpl(entryElement);
- myPersistentEntryPoints.put(entryPoint.getFQName(), entryPoint);
+ if (entryPointsElement != null) {
+ final String version = entryPointsElement.getAttributeValue(VERSION_ATTR);
+ if (!Comparing.strEqual(version, VERSION)) {
+ convert(entryPointsElement, myPersistentEntryPoints);
+ }
+ else {
+ List content = entryPointsElement.getChildren();
+ for (final Object aContent : content) {
+ Element entryElement = (Element)aContent;
+ if (ENTRY_POINT_ATTR.equals(entryElement.getName())) {
+ SmartRefElementPointerImpl entryPoint = new SmartRefElementPointerImpl(entryElement);
+ myPersistentEntryPoints.put(entryPoint.getFQName(), entryPoint);
+ }
}
}
}
@Override
public void configureAnnotations() {
- final JPanel listPanel = SpecialAnnotationsUtil.createSpecialAnnotationsListControl(ADDITIONAL_ANNOTATIONS, "Do not check if annotated by");
+ final JPanel listPanel = SpecialAnnotationsUtil.createSpecialAnnotationsListControl(ADDITIONAL_ANNOTATIONS, "Do not check if annotated by", true);
new DialogWrapper(myProject) {
{
init();
private static final int ASSIGNED_ONLY_IN_INITIALIZER = 0x40000;
RefFieldImpl(PsiField field, RefManager manager) {
- this((RefClass) manager.getReference(field.getContainingClass()), field, manager);
+ this((RefClass)((RefManagerImpl)manager).getReference(field.getContainingClass(), true), field, manager);
}
RefFieldImpl(RefClass ownerClass, PsiField field, RefManager manager) {
protected final RefClass myOwnerClass;
RefMethodImpl(PsiMethod method, RefManager manager) {
- this((RefClass) manager.getReference(method.getContainingClass()), method, manager);
+ this((RefClass)((RefManagerImpl)manager).getReference(method.getContainingClass(), true), method, manager);
}
RefMethodImpl(RefClass ownerClass, PsiMethod method, RefManager manager) {
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ex.InspectionProfileImpl;
import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection;
-import com.intellij.openapi.actionSystem.ActionManager;
-import com.intellij.openapi.actionSystem.ActionPlaces;
-import com.intellij.openapi.actionSystem.ActionToolbar;
-import com.intellij.openapi.actionSystem.DefaultActionGroup;
+import com.intellij.ide.DataManager;
+import com.intellij.ide.util.ClassFilter;
+import com.intellij.ide.util.TreeClassChooser;
+import com.intellij.ide.util.TreeClassChooserFactory;
+import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
+import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Factory;
+import com.intellij.openapi.util.IconLoader;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
+import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.ui.ReorderableListController;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SeparatorFactory;
*/
public class SpecialAnnotationsUtil {
public static JPanel createSpecialAnnotationsListControl(final List<String> list, final String borderTitle) {
+ return createSpecialAnnotationsListControl(list, borderTitle, false);
+ }
+
+ public static JPanel createSpecialAnnotationsListControl(final List<String> list, final String borderTitle, final boolean acceptPatterns) {
final SortedListModel<String> listModel = new SortedListModel<String>(new Comparator<String>() {
public int compare(final String o1, final String o2) {
return o1.compareTo(o2);
final ReorderableListController<String> controller = ReorderableListController.create(injectionList, actionGroup);
controller.addAddAction(InspectionsBundle.message("special.annotations.list.add.annotation.class"), new Factory<String>() {
public String create() {
- return Messages.showInputDialog(InspectionsBundle.message("special.annotations.list.annotation.class"),
- InspectionsBundle.message("special.annotations.list.add.annotation.class"),
- Messages.getQuestionIcon());
+ Project project = PlatformDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(injectionList));
+ if (project == null) project = ProjectManager.getInstance().getDefaultProject();
+ TreeClassChooser chooser = TreeClassChooserFactory.getInstance(project)
+ .createWithInnerClassesScopeChooser(InspectionsBundle.message("special.annotations.list.annotation.class"),
+ GlobalSearchScope.allScope(project), new ClassFilter() {
+ @Override
+ public boolean isAccepted(PsiClass aClass) {
+ return aClass.isAnnotationType();
+ }
+ }, null);
+ chooser.showDialog();
+ final PsiClass selected = chooser.getSelected();
+ return selected != null ? selected.getQualifiedName() : null;
}
}, true);
+ if (acceptPatterns) {
+ controller.addAction(new AnAction(InspectionsBundle.message("special.annotations.list.annotation.pattern"),
+ InspectionsBundle.message("special.annotations.list.annotation.pattern"),
+ IconLoader.getIcon("/general/add.png")) {
+ @Override
+ public void actionPerformed(AnActionEvent e) {
+ String selectedPattern = Messages.showInputDialog(InspectionsBundle.message("special.annotations.list.annotation.pattern"),
+ InspectionsBundle.message("special.annotations.list.annotation.pattern"),
+ Messages.getQuestionIcon());
+ if (selectedPattern != null) {
+ listModel.add(selectedPattern);
+ }
+ }
+ });
+ }
controller.addRemoveAction(InspectionsBundle.message("special.annotations.list.remove.annotation.class"));
injectionList.getModel().addListDataListener(new ListDataListener() {
public void intervalAdded(ListDataEvent e) {
private void listChanged() {
list.clear();
for (int i = 0; i < listModel.getSize(); i++) {
- list.add((String)listModel.getElementAt(i));
+ list.add((String)listModel.getElementAt(i));
}
}
*/
package com.intellij.codeInspection.varScopeCanBeNarrowed;
+import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.codeInsight.daemon.ImplicitUsageProvider;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.ex.BaseLocalInspectionTool;
+import com.intellij.codeInspection.util.SpecialAnnotationsUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.JDOMExternalizableStringList;
import com.intellij.openapi.util.Ref;
+import com.intellij.openapi.util.WriteExternalException;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.HashSet;
import gnu.trove.THashSet;
+import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import javax.swing.*;
+import java.awt.*;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.varScopeCanBeNarrowed.FieldCanBeLocalInspection");
@NonNls public static final String SHORT_NAME = "FieldCanBeLocal";
+ public final JDOMExternalizableStringList EXCLUDE_ANNOS = new JDOMExternalizableStringList();
@NotNull
public String getGroupDisplayName() {
return SHORT_NAME;
}
+ @Override
+ public void writeSettings(Element node) throws WriteExternalException {
+ if (!EXCLUDE_ANNOS.isEmpty()) {
+ super.writeSettings(node);
+ }
+ }
+
+ @Nullable
+ @Override
+ public JComponent createOptionsPanel() {
+ final JPanel listPanel = SpecialAnnotationsUtil
+ .createSpecialAnnotationsListControl(EXCLUDE_ANNOS, InspectionsBundle.message("special.annotations.annotations.list"));
+
+ final JPanel panel = new JPanel(new BorderLayout(2, 2));
+ panel.add(listPanel, BorderLayout.NORTH);
+ return panel;
+ }
+
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
@Override
public void visitJavaFile(PsiJavaFile file) {
for (PsiClass aClass : file.getClasses()) {
- docheckClass(aClass, holder);
+ docheckClass(aClass, holder, EXCLUDE_ANNOS);
}
}
};
}
- private static void docheckClass(final PsiClass aClass, ProblemsHolder holder) {
+ private static void docheckClass(final PsiClass aClass, ProblemsHolder holder, final List<String> excludeAnnos) {
if (aClass.isInterface()) return;
final PsiField[] fields = aClass.getFields();
final Set<PsiField> candidates = new LinkedHashSet<PsiField>();
for (PsiField field : fields) {
+ if (AnnotationUtil.isAnnotated(field, excludeAnnos)) {
+ continue;
+ }
if (field.hasModifierProperty(PsiModifier.PRIVATE) && !(field.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.FINAL))) {
candidates.add(field);
}
*/
package com.intellij.ide.projectView.impl;
+import com.intellij.history.LocalHistory;
+import com.intellij.history.LocalHistoryAction;
+import com.intellij.ide.DeleteProvider;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.SelectInTarget;
import com.intellij.ide.impl.PackagesPaneSelectInTarget;
import com.intellij.ide.projectView.impl.nodes.PackageElement;
import com.intellij.ide.projectView.impl.nodes.PackageUtil;
import com.intellij.ide.projectView.impl.nodes.PackageViewProjectNode;
+import com.intellij.ide.util.DeleteHandler;
import com.intellij.ide.util.treeView.AbstractTreeBuilder;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.ide.util.treeView.AbstractTreeStructure;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
+import java.util.*;
public final class PackageViewPane extends AbstractProjectViewPSIPane {
@NonNls public static final String ID = "PackagesPane";
public static final Icon ICON = IconLoader.getIcon("/general/packagesTab.png");
+ private MyDeletePSIElementProvider myDeletePSIElementProvider = new MyDeletePSIElementProvider();
public PackageViewPane(Project project) {
super(project);
@Override
public Object getData(final String dataId) {
+ if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.is(dataId)) {
+ final PackageElement selectedPackageElement = getSelectedPackageElement();
+ if (selectedPackageElement != null) {
+ return myDeletePSIElementProvider;
+ }
+ }
if (PackageElement.DATA_KEY.is(dataId)) {
final PackageElement packageElement = getSelectedPackageElement();
}
return modules.toArray(new Module[modules.size()]);
}
}
+
+ private final class MyDeletePSIElementProvider implements DeleteProvider {
+ public boolean canDeleteElement(DataContext dataContext) {
+ for (PsiDirectory directory : getSelectedDirectories()) {
+ if (!directory.getManager().isInProject(directory)) return false;
+ }
+ return true;
+ }
+
+ public void deleteElement(DataContext dataContext) {
+ List<PsiDirectory> allElements = Arrays.asList(getSelectedDirectories());
+ List<PsiElement> validElements = new ArrayList<PsiElement>();
+ for (PsiElement psiElement : allElements) {
+ if (psiElement != null && psiElement.isValid()) validElements.add(psiElement);
+ }
+ final PsiElement[] elements = validElements.toArray(new PsiElement[validElements.size()]);
+
+ LocalHistoryAction a = LocalHistory.getInstance().startAction(IdeBundle.message("progress.deleting"));
+ try {
+ DeleteHandler.deletePsiElement(elements, myProject);
+ }
+ finally {
+ a.finish();
+ }
+ }
+ }
}
final PrintWriter writer = new PrintWriter(new FileWriter(sourcepathTempFile));
try {
writer.println("-sourcepath");
- writer.println(OrderEnumerator.orderEntries(myProject).withoutSdk().withoutLibraries().getSourcePathsList().getPathsString());
+ writer.println(GeneralCommandLine.quote(OrderEnumerator.orderEntries(myProject).withoutSdk().withoutLibraries().getSourcePathsList().getPathsString()));
final Collection<String> packages = new HashSet<String>();
final Collection<String> sources = new HashSet<String>();
final Runnable findRunnable = new Runnable() {
import com.intellij.util.StringBuilderSpinAllocator;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
if (aClass instanceof PsiAnonymousClass) return LangBundle.message("java.terms.anonymous.class");
PsiFile file = aClass.getContainingFile();
- final Module module = ModuleUtil.findModuleForPsiElement(file);
- if (module != null) {
- buffer.append('[').append(module.getName()).append("] ");
+ final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(aClass.getProject()).getFileIndex();
+ VirtualFile vFile = file.getVirtualFile();
+ if (vFile != null && (fileIndex.isInLibrarySource(vFile) || fileIndex.isInLibraryClasses(vFile))) {
+ final List<OrderEntry> orderEntries = fileIndex.getOrderEntriesForFile(vFile);
+ if (orderEntries.size() > 0) {
+ final OrderEntry orderEntry = orderEntries.get(0);
+ buffer.append("[").append(orderEntry.getPresentableName()).append("] ");
+ }
+ }
+ else {
+ final Module module = ModuleUtil.findModuleForPsiElement(file);
+ if (module != null) {
+ buffer.append('[').append(module.getName()).append("] ");
+ }
}
if (file instanceof PsiJavaFile) {
public static String fetchExternalJavadoc(PsiElement element, final Project project, final List<String> docURLs) {
final JavaDocExternalFilter docFilter = new JavaDocExternalFilter(project);
+ return fetchExternalJavadoc(element, docURLs, docFilter);
+ }
+
+ public static String fetchExternalJavadoc(PsiElement element, List<String> docURLs, @NotNull JavaDocExternalFilter docFilter) {
if (docURLs != null) {
for (String docURL : docURLs) {
try {
}
// rename constructors
- PsiMethod[] methods = getMethods();
- for (PsiMethod method : methods) {
- if (method.isConstructor() && method.getName().equals(oldName)) {
+ for (PsiMethod method : getConstructors()) {
+ if (method.getName().equals(oldName)) {
method.setName(newName);
}
}
continue;
}
- PsiType returnType1 = method.getReturnType();
- PsiType returnType2 = existingMethod.getReturnType();
- if (returnType1 != null && returnType2 != null) {
- returnType1 = infoSubstitutor.substitute(returnType1);
- returnType2 = existing.getSubstitutor().substitute(returnType2);
- if (returnType1.isAssignableFrom(returnType2) &&
- (InheritanceUtil.isInheritorOrSelf(class1, existingClass, true) ||
- InheritanceUtil.isInheritorOrSelf(existingClass, class1, true))) {
- conflicts.remove(i);
- i--;
+ if (InheritanceUtil.isInheritorOrSelf(class1, existingClass, true) ||
+ InheritanceUtil.isInheritorOrSelf(existingClass, class1, true)) {
+ PsiParameter[] parameters = method.getParameterList().getParameters();
+ final PsiParameter[] existingParameters = existingMethod.getParameterList().getParameters();
+ for (int i1 = 0, parametersLength = parameters.length; i1 < parametersLength; i1++) {
+ if (parameters[i1].getType() instanceof PsiArrayType &&
+ !(existingParameters[i1].getType() instanceof PsiArrayType)) {//prefer more specific type
+ signatures.put(signature, info);
+ continue nextConflict;
+ }
+ }
+ PsiType returnType1 = method.getReturnType();
+ PsiType returnType2 = existingMethod.getReturnType();
+ if (returnType1 != null && returnType2 != null) {
+ returnType1 = infoSubstitutor.substitute(returnType1);
+ returnType2 = existing.getSubstitutor().substitute(returnType2);
+ if (returnType1.isAssignableFrom(returnType2)) {
+ conflicts.remove(i);
+ i--;
+ }
}
}
}
package com.intellij.psi.scope.util;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.progress.ProgressManager;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.infos.ClassCandidateInfo;
private PsiScopesUtil() {
}
- public static boolean treeWalkUp(@NotNull PsiScopeProcessor processor, @NotNull PsiElement entrance, @Nullable PsiElement maxScope) {
+ public static boolean treeWalkUp(@NotNull PsiScopeProcessor processor,
+ @NotNull PsiElement entrance,
+ @Nullable PsiElement maxScope) {
return treeWalkUp(processor, entrance, maxScope, ResolveState.initial());
}
- public static boolean treeWalkUp(@NotNull final PsiScopeProcessor processor, @NotNull final PsiElement entrance,
- @Nullable final PsiElement maxScope,
- @NotNull final ResolveState state) {
+ public static boolean treeWalkUp(@NotNull final PsiScopeProcessor processor,
+ @NotNull final PsiElement entrance,
+ @Nullable final PsiElement maxScope,
+ @NotNull final ResolveState state) {
PsiElement prevParent = entrance;
PsiElement scope = entrance;
- while(scope != null){
- if(scope instanceof PsiClass){
+ while (scope != null) {
+ ProgressManager.checkCanceled();
+ if (scope instanceof PsiClass) {
processor.handleEvent(JavaScopeProcessorEvent.SET_CURRENT_FILE_CONTEXT, scope);
}
if (!scope.processDeclarations(processor, state, prevParent, entrance)) {
return false; // resolved
}
- if (scope instanceof PsiModifierListOwner && !(scope instanceof PsiParameter/* important for not loading tree! */)){
+ if (scope instanceof PsiModifierListOwner && !(scope instanceof PsiParameter/* important for not loading tree! */)) {
PsiModifierList modifierList = ((PsiModifierListOwner)scope).getModifierList();
- if (modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC)){
+ if (modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC)) {
processor.handleEvent(JavaScopeProcessorEvent.START_STATIC, null);
}
}
return true;
}
- public static boolean walkChildrenScopes(PsiElement thisElement, PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place) {
+ public static boolean walkChildrenScopes(@NotNull PsiElement thisElement,
+ @NotNull PsiScopeProcessor processor,
+ @NotNull ResolveState state,
+ PsiElement lastParent,
+ PsiElement place) {
PsiElement child = null;
- if (lastParent != null && lastParent.getParent() == thisElement){
+ if (lastParent != null && lastParent.getParent() == thisElement) {
child = lastParent.getPrevSibling();
if (child == null) return true; // first element
}
- if (child == null){
+ if (child == null) {
child = thisElement.getLastChild();
}
- while(child != null){
+ while (child != null) {
if (!child.processDeclarations(processor, state, null, place)) return false;
child = child.getPrevSibling();
}
return resolveAndWalk(processor, ref, maxScope, false);
}
- public static boolean resolveAndWalk(PsiScopeProcessor processor, PsiJavaCodeReferenceElement ref, PsiElement maxScope, boolean incompleteCode) {
+ public static boolean resolveAndWalk(PsiScopeProcessor processor,
+ PsiJavaCodeReferenceElement ref,
+ PsiElement maxScope,
+ boolean incompleteCode) {
final PsiElement qualifier = ref.getQualifier();
final PsiElement classNameElement = ref.getReferenceNameElement();
- if(classNameElement == null) return true;
- if (qualifier != null){
+ if (classNameElement == null) return true;
+ if (qualifier != null) {
// Composite expression
- final PsiElementFactory factory = JavaPsiFacade.getInstance(ref.getProject()).getElementFactory();
PsiElement target = null;
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
- if (qualifier instanceof PsiExpression || qualifier instanceof PsiJavaCodeReferenceElement){
+ if (qualifier instanceof PsiExpression || qualifier instanceof PsiJavaCodeReferenceElement) {
PsiType type = null;
- if(qualifier instanceof PsiExpression){
+ if (qualifier instanceof PsiExpression) {
type = ((PsiExpression)qualifier).getType();
final ClassCandidateInfo result = TypeConversionUtil.splitType(type, qualifier);
if (result != null) {
}
}
- if(type == null && qualifier instanceof PsiJavaCodeReferenceElement) {
+ if (type == null && qualifier instanceof PsiJavaCodeReferenceElement) {
// In case of class qualifier
final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement)qualifier;
final JavaResolveResult result = referenceElement.advancedResolve(incompleteCode);
target = result.getElement();
substitutor = result.getSubstitutor();
- if(target instanceof PsiVariable){
- type = substitutor.substitute(((PsiVariable) target).getType());
- if(type instanceof PsiClassType){
- final JavaResolveResult typeResult = ((PsiClassType) type).resolveGenerics();
+ if (target instanceof PsiVariable) {
+ type = substitutor.substitute(((PsiVariable)target).getType());
+ if (type instanceof PsiClassType) {
+ final JavaResolveResult typeResult = ((PsiClassType)type).resolveGenerics();
target = typeResult.getElement();
substitutor = substitutor.putAll(typeResult.getSubstitutor());
}
- else target = null;
+ else {
+ target = null;
+ }
}
- else if(target instanceof PsiMethod){
- type = substitutor.substitute(((PsiMethod) target).getReturnType());
- if(type instanceof PsiClassType){
- final JavaResolveResult typeResult = ((PsiClassType) type).resolveGenerics();
+ else if (target instanceof PsiMethod) {
+ type = substitutor.substitute(((PsiMethod)target).getReturnType());
+ if (type instanceof PsiClassType) {
+ final JavaResolveResult typeResult = ((PsiClassType)type).resolveGenerics();
target = typeResult.getElement();
substitutor = substitutor.putAll(typeResult.getSubstitutor());
}
- else target = null;
+ else {
+ target = null;
+ }
final PsiType[] types = referenceElement.getTypeParameters();
- if(target instanceof PsiClass) {
+ if (target instanceof PsiClass) {
substitutor = substitutor.putAll((PsiClass)target, types);
}
}
- else if(target instanceof PsiClass){
+ else if (target instanceof PsiClass) {
processor.handleEvent(JavaScopeProcessorEvent.START_STATIC, null);
}
}
}
- if(target != null) return target.processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, substitutor), target, ref);
+ if (target != null) {
+ return target.processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, substitutor), target, ref);
+ }
}
- else{
+ else {
// simple expression -> trying to resolve variable or method
return treeWalkUp(processor, ref, maxScope);
}
}
public static void setupAndRunProcessor(MethodsProcessor processor, PsiCallExpression call, boolean dummyImplicitConstructor)
- throws MethodProcessorSetupFailedException{
- if (call instanceof PsiMethodCallExpression){
+ throws MethodProcessorSetupFailedException {
+ if (call instanceof PsiMethodCallExpression) {
final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)call;
final PsiJavaCodeReferenceElement ref = methodCall.getMethodExpression();
processor.setArgumentList(methodCall.getArgumentList());
processor.obtainTypeArguments(methodCall);
- if (!ref.isQualified() || ref.getReferenceNameElement() instanceof PsiKeyword){
+ if (!ref.isQualified() || ref.getReferenceNameElement() instanceof PsiKeyword) {
final PsiElement referenceNameElement = ref.getReferenceNameElement();
if (referenceNameElement == null) return;
- if (referenceNameElement instanceof PsiKeyword){
+ if (referenceNameElement instanceof PsiKeyword) {
final PsiKeyword keyword = (PsiKeyword)referenceNameElement;
- if (keyword.getTokenType() == JavaTokenType.THIS_KEYWORD){
+ if (keyword.getTokenType() == JavaTokenType.THIS_KEYWORD) {
final PsiClass aClass = JavaResolveUtil.getContextClass(methodCall);
if (aClass == null) {
throw new MethodProcessorSetupFailedException("Can't resolve class for this expression");
processor.setAccessClass(aClass);
aClass.processDeclarations(processor, ResolveState.initial(), null, call);
- if (dummyImplicitConstructor){
+ if (dummyImplicitConstructor) {
processDummyConstructor(processor, aClass);
}
}
- else if (keyword.getTokenType() == JavaTokenType.SUPER_KEYWORD){
+ else if (keyword.getTokenType() == JavaTokenType.SUPER_KEYWORD) {
PsiClass aClass = JavaResolveUtil.getContextClass(methodCall);
if (aClass == null) {
throw new MethodProcessorSetupFailedException("Can't resolve class for super expression");
}
while (aClass != null);
//apply substitutors in 'outer classes down to inner classes' order because inner class subst take precedence
- for (int i = contextSubstitutors.size()-1; i>=0; i--) {
+ for (int i = contextSubstitutors.size() - 1; i >= 0; i--) {
PsiSubstitutor contextSubstitutor = contextSubstitutors.get(i);
substitutor = substitutor.putAll(contextSubstitutor);
}
if (dummyImplicitConstructor) processDummyConstructor(processor, superClass);
}
}
- else{
+ else {
LOG.error("Unknown name element " + referenceNameElement + " in reference " + ref.getText() + "(" + ref + ")");
}
}
- else if (referenceNameElement instanceof PsiIdentifier){
+ else if (referenceNameElement instanceof PsiIdentifier) {
processor.setIsConstructor(false);
processor.setName(referenceNameElement.getText());
processor.setAccessClass(null);
resolveAndWalk(processor, ref, null);
}
- else{
+ else {
LOG.error("Unknown name element " + referenceNameElement + " in reference " + ref.getText() + "(" + ref + ")");
}
}
- else{
+ else {
// Complex expression
final PsiElement referenceName = methodCall.getMethodExpression().getReferenceNameElement();
final PsiManager manager = call.getManager();
final PsiElement qualifier = ref.getQualifier();
- if (referenceName instanceof PsiIdentifier && qualifier instanceof PsiExpression){
- PsiType type = ((PsiExpression) qualifier).getType();
+ if (referenceName instanceof PsiIdentifier && qualifier instanceof PsiExpression) {
+ PsiType type = ((PsiExpression)qualifier).getType();
if (type == null) {
if (qualifier instanceof PsiJavaCodeReferenceElement) {
- final JavaResolveResult result = ((PsiJavaCodeReferenceElement) qualifier).advancedResolve(false);
+ final JavaResolveResult result = ((PsiJavaCodeReferenceElement)qualifier).advancedResolve(false);
if (result.getElement() instanceof PsiClass) {
processor.handleEvent(JavaScopeProcessorEvent.START_STATIC, null);
processQualifierResult(result, processor, methodCall);
else {
throw new MethodProcessorSetupFailedException("Cant determine qualifier type!");
}
- } else if (type instanceof PsiIntersectionType) {
+ }
+ else if (type instanceof PsiIntersectionType) {
final PsiType[] conjuncts = ((PsiIntersectionType)type).getConjuncts();
for (PsiType conjunct : conjuncts) {
if (!processQualifierType(conjunct, processor, manager, methodCall)) break;
}
- } else {
+ }
+ else {
processQualifierType(type, processor, manager, methodCall);
}
}
- else{
+ else {
LOG.assertTrue(false);
}
}
- } else{
+ }
+ else {
LOG.assertTrue(call instanceof PsiNewExpression);
PsiNewExpression newExpr = (PsiNewExpression)call;
PsiJavaCodeReferenceElement classRef = newExpr.getClassOrAnonymousClassReference();
}
final JavaResolveResult result = classRef.advancedResolve(false);
- PsiClass aClass = (PsiClass) result.getElement();
- if (aClass == null)
+ PsiClass aClass = (PsiClass)result.getElement();
+ if (aClass == null) {
throw new MethodProcessorSetupFailedException("Cant resolve class in new expression");
+ }
processor.setIsConstructor(true);
processor.setAccessClass(aClass);
processor.setArgumentList(newExpr.getArgumentList());
processor.obtainTypeArguments(newExpr);
aClass.processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, result.getSubstitutor()), null, call);
- if (dummyImplicitConstructor){
+ if (dummyImplicitConstructor) {
processDummyConstructor(processor, aClass);
}
}
}
private static boolean processQualifierType(final PsiType type,
- final MethodsProcessor processor,
- PsiManager manager,
- PsiMethodCallExpression call) throws MethodProcessorSetupFailedException {
+ final MethodsProcessor processor,
+ PsiManager manager,
+ PsiMethodCallExpression call) throws MethodProcessorSetupFailedException {
if (type instanceof PsiClassType) {
JavaResolveResult qualifierResult = ((PsiClassType)type).resolveGenerics();
return processQualifierResult(qualifierResult, processor, call);
}
else if (type instanceof PsiArrayType) {
LanguageLevel languageLevel = PsiUtil.getLanguageLevel(call);
- JavaResolveResult qualifierResult = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().getArrayClassType(((PsiArrayType)type).getComponentType(),
- languageLevel).resolveGenerics();
+ PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
+ JavaResolveResult qualifierResult =
+ factory.getArrayClassType(((PsiArrayType)type).getComponentType(), languageLevel).resolveGenerics();
return processQualifierResult(qualifierResult, processor, call);
}
else if (type instanceof PsiIntersectionType) {
}
private static boolean processQualifierResult(JavaResolveResult qualifierResult,
- final MethodsProcessor processor,
- PsiMethodCallExpression methodCall) throws MethodProcessorSetupFailedException {
+ final MethodsProcessor processor,
+ PsiMethodCallExpression methodCall) throws MethodProcessorSetupFailedException {
PsiElement resolve = qualifierResult.getElement();
- if (resolve == null)
+ if (resolve == null) {
throw new MethodProcessorSetupFailedException("Cant determine qualifier class!");
+ }
if (resolve instanceof PsiTypeParameter) {
processor.setAccessClass((PsiClass)resolve);
processor.setIsConstructor(false);
processor.setName(methodCall.getMethodExpression().getReferenceName());
- return resolve.processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, qualifierResult.getSubstitutor()), methodCall, methodCall);
+ ResolveState state = ResolveState.initial().put(PsiSubstitutor.KEY, qualifierResult.getSubstitutor());
+ return resolve.processDeclarations(processor, state, methodCall, methodCall);
}
private static void processDummyConstructor(MethodsProcessor processor, PsiClass aClass) {
if (aClass instanceof PsiAnonymousClass) return;
- try{
- PsiMethod[] methods = aClass.getMethods();
- for (PsiMethod method : methods) {
- if (method.isConstructor()) {
- return;
- }
+ try {
+ PsiMethod[] constructors = aClass.getConstructors();
+ if (constructors.length != 0) {
+ return;
}
final PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory();
final PsiMethod dummyConstructor = factory.createConstructor();
- if(aClass.getNameIdentifier() != null){
- dummyConstructor.getNameIdentifier().replace(aClass.getNameIdentifier());
+ PsiIdentifier nameIdentifier = aClass.getNameIdentifier();
+ if (nameIdentifier != null) {
+ dummyConstructor.getNameIdentifier().replace(nameIdentifier);
}
processor.forceAddResult(dummyConstructor);
}
- catch(IncorrectOperationException e){
+ catch (IncorrectOperationException e) {
LOG.error(e);
}
}
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
+import com.intellij.psi.util.PsiExpressionTrimRenderer;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.IntroduceTargetChooser;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
-import com.intellij.refactoring.introduceVariable.PsiExpressionTrimRenderer;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.refactoring.util.duplicates.DuplicatesImpl;
/**
* @author ven
*/
-class InlineConstantFieldProcessor extends BaseRefactoringProcessor {
+public class InlineConstantFieldProcessor extends BaseRefactoringProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.inline.InlineConstantFieldProcessor");
private PsiField myField;
private final PsiReferenceExpression myRefExpr;
private final boolean myInlineThisOnly;
- InlineConstantFieldProcessor(PsiField field, Project project, PsiReferenceExpression ref, boolean isInlineThisOnly) {
+ public InlineConstantFieldProcessor(PsiField field, Project project, PsiReferenceExpression ref, boolean isInlineThisOnly) {
super(project);
myField = field;
myRefExpr = ref;
if (blockData.thisVar != null) {
PsiExpression qualifier = methodCall.getMethodExpression().getQualifierExpression();
if (qualifier == null) {
- PsiElement parent = methodCall.getParent();
+ PsiElement parent = methodCall.getContext();
while (true) {
if (parent instanceof PsiClass) break;
if (parent instanceof PsiFile) break;
- parent = parent.getParent();
+ assert parent != null : methodCall;
+ parent = parent.getContext();
}
if (parent instanceof PsiClass) {
PsiClass parentClass = (PsiClass)parent;
import com.intellij.refactoring.IntroduceTargetChooser;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
-import com.intellij.refactoring.introduceVariable.PsiExpressionTrimRenderer;
+import com.intellij.psi.util.PsiExpressionTrimRenderer;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import java.util.List;
if (myRbInSetUp != null) myRbInSetUp.setEnabled(false);
}
- if (ourLastInitializerPlace == IN_CONSTRUCTOR) {
+ final PsiMethod setUpMethod = TestUtil.findSetUpMethod(myParentClass);
+ if (myInitializerExpression != null && PsiTreeUtil.isAncestor(setUpMethod, myInitializerExpression, false) && myRbInSetUp.isEnabled() ||
+ ourLastInitializerPlace == IN_SETUP_METHOD && TestUtil.isTestClass(myParentClass) && myRbInSetUp.isEnabled()) {
+ myRbInSetUp.setSelected(true);
+ }
+ else if (ourLastInitializerPlace == IN_CONSTRUCTOR) {
if (myRbInConstructor.isEnabled()) {
myRbInConstructor.setSelected(true);
} else {
} else {
selectInCurrentMethod();
}
- } else if (ourLastInitializerPlace == IN_SETUP_METHOD && TestUtil.isTestClass(myParentClass) && myRbInSetUp.isEnabled()) {
- myRbInSetUp.setSelected(true);
} else {
selectInCurrentMethod();
}
myRbProtected.setSelected(true);
} else if (PsiModifier.PACKAGE_LOCAL.equals(ourLastVisibility)) {
myRbPackageLocal.setSelected(true);
- } else if (PsiModifier.PRIVATE.equals(ourLastVisibility)) {
- myRbPrivate.setSelected(true);
} else {
myRbPrivate.setSelected(true);
}
int occurencesNumber = occurences.length;
final boolean currentMethodConstructor = containingMethod != null && containingMethod.isConstructor();
- final boolean allowInitInMethod = (!currentMethodConstructor || !isInSuperOrThis) && anchorElement instanceof PsiLocalVariable;
+ final boolean allowInitInMethod = (!currentMethodConstructor || !isInSuperOrThis) && (anchorElement instanceof PsiLocalVariable || anchorElement instanceof PsiStatement);
final boolean allowInitInMethodIfAll = (!currentMethodConstructor || !isInSuperOrThis) && anchorElementIfAll instanceof PsiStatement;
IntroduceFieldDialog dialog = new IntroduceFieldDialog(
project, parentClass, expr, localVariable,
currentMethodConstructor,
- false, declareStatic, occurencesNumber,
+ localVariable != null, declareStatic, occurencesNumber,
allowInitInMethod, allowInitInMethodIfAll,
new TypeSelectorManagerImpl(project, type, containingMethod, expr, occurences)
);