diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java index dbdb99cf8bcf..ed620fa7b229 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java @@ -228,6 +228,7 @@ public class CompileDriver { } finally { compileContext.commitZipFiles(); // just to be on the safe side; normally should do nothing if called in isUpToDate() + CompilerCacheManager.getInstance(myProject).flushCaches(); } } }, null); @@ -455,6 +456,7 @@ public class CompileDriver { compileContext.getMessageCount(CompilerMessageCategory.WARNING), finish - start ); + CompilerCacheManager.getInstance(myProject).flushCaches(); //if (LOG.isDebugEnabled()) { // LOG.debug("COMPILATION FINISHED"); //} @@ -792,7 +794,6 @@ public class CompileDriver { finally { // drop in case it has not been dropped yet. dropDependencyCache(context); - final VirtualFile[] allOutputDirs = context.getAllOutputDirectories(); if (didSomething && GENERATE_CLASSPATH_INDEX) { diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompilerCacheManager.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompilerCacheManager.java index 4ae6a77d6c86..5c147ee644a1 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompilerCacheManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompilerCacheManager.java @@ -23,8 +23,6 @@ import com.intellij.openapi.compiler.generic.GenericCompiler; 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; @@ -48,14 +46,6 @@ public class CompilerCacheManager implements ProjectComponent { private final Map, GenericCompilerCache> myGenericCachesMap = new HashMap, GenericCompilerCache>(); private final List myCacheDisposables = new ArrayList(); 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) { @@ -68,18 +58,9 @@ public class CompilerCacheManager implements ProjectComponent { } 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 @@ -101,15 +82,17 @@ public class CompilerCacheManager implements ProjectComponent { } public synchronized GenericCompilerCache - getGenericCompilerCache(GenericCompiler compiler) throws IOException { + getGenericCompilerCache(final GenericCompiler compiler) throws IOException { GenericCompilerCache cache = myGenericCachesMap.get(compiler); if (cache == null) { final GenericCompilerCache genericCache = new GenericCompilerCache(compiler, GenericCompilerRunner .getGenericCompilerCacheDir(myProject, compiler)); myGenericCachesMap.put(compiler, genericCache); myCacheDisposables.add(new Disposable() { - @Override public void dispose() { + if (LOG.isDebugEnabled()) { + LOG.debug("Closing cache for feneric compiler " + compiler.getId()); + } genericCache.close(); } }); @@ -119,15 +102,17 @@ public class CompilerCacheManager implements ProjectComponent { return (GenericCompilerCache)cache; } - public synchronized FileProcessingCompilerStateCache getFileProcessingCompilerCache(FileProcessingCompiler compiler) throws IOException { + public synchronized FileProcessingCompilerStateCache getFileProcessingCompilerCache(final FileProcessingCompiler compiler) throws IOException { Object cache = myCompilerToCacheMap.get(compiler); if (cache == null) { - final FileProcessingCompilerStateCache stateCache = new FileProcessingCompilerStateCache(getCompilerRootDir(compiler), - compiler - ); + final File compilerRootDir = getCompilerRootDir(compiler); + final FileProcessingCompilerStateCache stateCache = new FileProcessingCompilerStateCache(compilerRootDir, compiler); myCompilerToCacheMap.put(compiler, stateCache); myCacheDisposables.add(new Disposable() { public void dispose() { + if (LOG.isDebugEnabled()) { + LOG.debug("Closing cache for compiler " + compiler.getDescription() + "; cache root dir: " + compilerRootDir); + } stateCache.close(); } }); diff --git a/java/compiler/impl/src/com/intellij/compiler/make/CachedPersistentHashMap.java b/java/compiler/impl/src/com/intellij/compiler/make/CachedPersistentHashMap.java index 0bb6773644c1..12eb05e551e3 100644 --- a/java/compiler/impl/src/com/intellij/compiler/make/CachedPersistentHashMap.java +++ b/java/compiler/impl/src/com/intellij/compiler/make/CachedPersistentHashMap.java @@ -103,7 +103,7 @@ public class CachedPersistentHashMap extends PersistentHashMap locationsOfLine(ReferenceType type, - SourcePosition position) { + public List locationsOfLine(ReferenceType type, SourcePosition position) throws NoDataException { try { int line = position.getLine() + 1; - List locs = (getDebugProcess().getVirtualMachineProxy().versionHigher("1.4") ? type.locationsOfLine(DebugProcessImpl.JAVA_STRATUM, null, line) : type.locationsOfLine(line)); + List locs = (getDebugProcess().getVirtualMachineProxy().versionHigher("1.4") + ? type.locationsOfLine(DebugProcessImpl.JAVA_STRATUM, null, line) : type.locationsOfLine(line)); if (locs.size() > 0) { return locs; } @@ -73,20 +74,20 @@ public class PositionManagerImpl implements PositionManager { return Collections.emptyList(); } - public ClassPrepareRequest createPrepareRequest(final ClassPrepareRequestor requestor, final SourcePosition position) { + public ClassPrepareRequest createPrepareRequest(final ClassPrepareRequestor requestor, final SourcePosition position) throws NoDataException { final Ref waitPrepareFor = new Ref(null); final Ref waitRequestor = new Ref(null); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { PsiClass psiClass = JVMNameUtil.getClassAt(position); - if(psiClass == null) { + if (psiClass == null) { return; } - if(PsiUtil.isLocalOrAnonymousClass(psiClass)) { + if (PsiUtil.isLocalOrAnonymousClass(psiClass)) { PsiClass parent = JVMNameUtil.getTopLevelParentClass(psiClass); - if(parent == null) { + if (parent == null) { return; } @@ -122,7 +123,7 @@ public class PositionManagerImpl implements PositionManager { return myDebugProcess.getRequestsManager().createClassPrepareRequest(waitRequestor.get(), waitPrepareFor.get()); } - public SourcePosition getSourcePosition(final Location location) { + public SourcePosition getSourcePosition(final Location location) throws NoDataException { DebuggerManagerThreadImpl.assertIsManagerThread(); if(location == null) { return null; @@ -204,7 +205,7 @@ public class PositionManagerImpl implements PositionManager { } @NotNull - public List getAllClasses(final SourcePosition classPosition) { + public List getAllClasses(final SourcePosition classPosition) throws NoDataException { final Trinity trinity = calcClassName(classPosition); if (trinity == null) { return Collections.emptyList(); @@ -231,7 +232,7 @@ public class PositionManagerImpl implements PositionManager { @Nullable private static Trinity calcClassName(final SourcePosition classPosition) { - return ApplicationManager.getApplication().runReadAction(new Computable> () { + return ApplicationManager.getApplication().runReadAction(new NullableComputable>() { public Trinity compute() { final PsiClass psiClass = JVMNameUtil.getClassAt(classPosition); @@ -296,7 +297,7 @@ public class PositionManagerImpl implements PositionManager { // First offsets belong to parent class, and offsets inside te substring "new Runnable(){" belong to anonymous runnable. final int finalRangeBegin = rangeBegin; final int finalRangeEnd = rangeEnd; - return ApplicationManager.getApplication().runReadAction(new Computable() { + return ApplicationManager.getApplication().runReadAction(new NullableComputable() { public ReferenceType compute() { final int line = Math.min(finalRangeBegin + 1, finalRangeEnd); final SourcePosition candidatePosition = SourcePosition.createFromLine(classToFind.getContainingFile(), line); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/Breakpoint.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/Breakpoint.java index 600d362a8094..0dafd39824e5 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/Breakpoint.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/Breakpoint.java @@ -31,7 +31,6 @@ import com.intellij.debugger.jdi.StackFrameProxyImpl; 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; @@ -41,14 +40,13 @@ import com.sun.jdi.ReferenceType; 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; @@ -134,7 +132,7 @@ public abstract class Breakpoint extends FilteredRequestor implements ClassPrepa } 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) { @@ -163,7 +161,7 @@ public abstract class Breakpoint extends FilteredRequestor implements ClassPrepa 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); @@ -245,7 +243,7 @@ public abstract class Breakpoint extends FilteredRequestor implements ClassPrepa updateUI(EmptyRunnable.getInstance()); } - public void updateUI(final Runnable afterUpdate) { + public void updateUI(@NotNull Runnable afterUpdate) { } public void delete() { diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointPropertiesPanel.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointPropertiesPanel.java index 48527a7e4c76..4eff6bc5adcf 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointPropertiesPanel.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointPropertiesPanel.java @@ -36,6 +36,7 @@ import com.intellij.openapi.ui.ComboBox; 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; @@ -90,7 +91,7 @@ public abstract class BreakpointPropertiesPanel { 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; @@ -220,8 +221,7 @@ public abstract class BreakpointPropertiesPanel { public void actionPerformed(ActionEvent e) { reloadClassFilters(); - ClassFilter classFilter; - classFilter = createClassConditionFilter(); + ClassFilter classFilter = createClassConditionFilter(); EditClassFiltersDialog _dialog = new EditClassFiltersDialog(myProject, classFilter); _dialog.setFilters(myClassFilters, myClassExclusionFilters); @@ -321,7 +321,7 @@ public abstract class BreakpointPropertiesPanel { */ 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); @@ -367,7 +367,7 @@ public abstract class BreakpointPropertiesPanel { /** * 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(); @@ -379,11 +379,11 @@ public abstract class BreakpointPropertiesPanel { } 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(); @@ -391,8 +391,8 @@ public abstract class BreakpointPropertiesPanel { 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); @@ -402,21 +402,11 @@ public abstract class BreakpointPropertiesPanel { breakpoint.updateUI(afterUpdate); } - private String concatWith(List 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 s, String concator) { + return StringUtil.join(s, concator); } - private String concatWithEx(List s, String concator, int N, String NthConcator) { + private static String concatWithEx(List s, String concator, int N, String NthConcator) { String result = ""; int i = 1; for (Iterator iterator = s.iterator(); iterator.hasNext(); i++) { @@ -435,9 +425,8 @@ public abstract class BreakpointPropertiesPanel { private void updateInstanceFilterEditor(boolean updateText) { List filters = new ArrayList(); - 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())); } } @@ -465,38 +454,35 @@ public abstract class BreakpointPropertiesPanel { } } } - 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 filters = new ArrayList(); - 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 excludeFilters = new ArrayList(); - 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); @@ -522,13 +508,11 @@ public abstract class BreakpointPropertiesPanel { } } } - 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()]); @@ -537,18 +521,17 @@ public abstract class BreakpointPropertiesPanel { 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; } } @@ -559,8 +542,8 @@ public abstract class BreakpointPropertiesPanel { 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()); @@ -597,9 +580,8 @@ public abstract class BreakpointPropertiesPanel { } 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); } @@ -636,7 +618,7 @@ public abstract class BreakpointPropertiesPanel { } public int hashCode() { - return (breakpoint != null ? breakpoint.hashCode() : 0); + return breakpoint != null ? breakpoint.hashCode() : 0; } } @@ -705,8 +687,9 @@ public abstract class BreakpointPropertiesPanel { 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; diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointWithHighlighter.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointWithHighlighter.java index e7344f03245d..45e9f5bdc89f 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointWithHighlighter.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointWithHighlighter.java @@ -69,7 +69,7 @@ public abstract class BreakpointWithHighlighter extends Breakpoint { 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; @@ -317,7 +317,7 @@ public abstract class BreakpointWithHighlighter extends Breakpoint { /** * 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; } @@ -359,8 +359,9 @@ public abstract class BreakpointWithHighlighter extends Breakpoint { 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); @@ -369,7 +370,7 @@ public abstract class BreakpointWithHighlighter extends Breakpoint { } /** - * called by BreakpointManeger when destroying the breakpoint + * called by BreakpointManager when destroying the breakpoint */ public void delete() { if (isVisible()) { @@ -414,9 +415,9 @@ public abstract class BreakpointWithHighlighter extends Breakpoint { }); } - private void setupGutterRenderer() { + private void setupGutterRenderer(@NotNull RangeHighlighter highlighter) { MyGutterIconRenderer renderer = new MyGutterIconRenderer(getIcon(), getDescription()); - getHighlighter().setGutterIconRenderer(renderer); + highlighter.setGutterIconRenderer(renderer); } public abstract Key getCategory(); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/ExceptionBreakpointPropertiesPanel.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/ExceptionBreakpointPropertiesPanel.java index 9de67e05caa9..5f55eb9c5ea6 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/ExceptionBreakpointPropertiesPanel.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/ExceptionBreakpointPropertiesPanel.java @@ -23,6 +23,7 @@ package com.intellij.debugger.ui.breakpoints; 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.*; @@ -99,7 +100,7 @@ public class ExceptionBreakpointPropertiesPanel extends BreakpointPropertiesPane 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(); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpointPropertiesPanel.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpointPropertiesPanel.java index 4627d9317a32..476b47988e99 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpointPropertiesPanel.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/FieldBreakpointPropertiesPanel.java @@ -22,6 +22,7 @@ package com.intellij.debugger.ui.breakpoints; import com.intellij.debugger.DebuggerBundle; import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; @@ -90,7 +91,7 @@ public class FieldBreakpointPropertiesPanel extends BreakpointPropertiesPanel { 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(); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/MethodBreakpointPropertiesPanel.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/MethodBreakpointPropertiesPanel.java index 65b0541cb3c7..d09bcd2443a8 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/MethodBreakpointPropertiesPanel.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/MethodBreakpointPropertiesPanel.java @@ -22,6 +22,7 @@ package com.intellij.debugger.ui.breakpoints; import com.intellij.debugger.DebuggerBundle; import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; @@ -95,7 +96,7 @@ public class MethodBreakpointPropertiesPanel extends BreakpointPropertiesPanel { } } - 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(); diff --git a/java/debugger/openapi/src/com/intellij/debugger/PositionManager.java b/java/debugger/openapi/src/com/intellij/debugger/PositionManager.java index 25ae15040929..9abc634e8fe6 100644 --- a/java/debugger/openapi/src/com/intellij/debugger/PositionManager.java +++ b/java/debugger/openapi/src/com/intellij/debugger/PositionManager.java @@ -25,16 +25,15 @@ import org.jetbrains.annotations.Nullable; import java.util.List; public interface PositionManager { - @Nullable SourcePosition getSourcePosition(Location location) throws NoDataException; @NotNull List getAllClasses(SourcePosition classPosition) throws NoDataException; - + @NotNull - List locationsOfLine (ReferenceType type, SourcePosition position) throws NoDataException; + List locationsOfLine(ReferenceType type, SourcePosition position) throws NoDataException; @Nullable - ClassPrepareRequest createPrepareRequest(ClassPrepareRequestor requestor, SourcePosition position)throws NoDataException; + ClassPrepareRequest createPrepareRequest(ClassPrepareRequestor requestor, SourcePosition position) throws NoDataException; } diff --git a/java/execution/impl/src/com/intellij/execution/application/ApplicationConfigurationProducer.java b/java/execution/impl/src/com/intellij/execution/application/ApplicationConfigurationProducer.java index c67d74a6f5f8..727d58de3b93 100644 --- a/java/execution/impl/src/com/intellij/execution/application/ApplicationConfigurationProducer.java +++ b/java/execution/impl/src/com/intellij/execution/application/ApplicationConfigurationProducer.java @@ -47,7 +47,7 @@ public class ApplicationConfigurationProducer extends JavaRuntimeConfigurationPr location = JavaExecutionUtil.stepIntoSingleClass(location); if (location == null) return null; final PsiElement element = location.getPsiElement(); - + if (!element.isPhysical()) return null; PsiElement currentElement = element; PsiMethod method; while ((method = findMain(currentElement)) != null) { diff --git a/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java b/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java index 1ea21942f526..d1f3a87c5633 100644 --- a/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java +++ b/java/execution/impl/src/com/intellij/execution/junit/JUnitUtil.java @@ -31,6 +31,7 @@ import com.intellij.psi.util.TypeConversionUtil; 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; @@ -209,6 +210,18 @@ public class JUnitUtil { 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 { private final PsiClass myClass; diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/AddCustomLibraryDialog.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/AddCustomLibraryDialog.java index cd81ce3f6ab7..94787a4d0885 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/AddCustomLibraryDialog.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraries/AddCustomLibraryDialog.java @@ -29,7 +29,7 @@ import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContaine import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.ParametrizedRunnable; +import com.intellij.util.ParameterizedRunnable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -45,13 +45,13 @@ public class AddCustomLibraryDialog extends DialogWrapper { private final LibrariesContainer myLibrariesContainer; private final Module myModule; private final ModifiableRootModel myModifiableRootModel; - private final @Nullable ParametrizedRunnable myBeforeLibraryAdded; + private final @Nullable ParameterizedRunnable myBeforeLibraryAdded; private final List myAddedLibraries = new ArrayList(); private AddCustomLibraryDialog(CustomLibraryDescription description, LibrariesContainer librariesContainer, Module module, ModifiableRootModel modifiableRootModel, - @Nullable ParametrizedRunnable beforeLibraryAdded) { + @Nullable ParameterizedRunnable beforeLibraryAdded) { super(module.getProject(), true); myLibrariesContainer = librariesContainer; myModule = module; @@ -68,14 +68,14 @@ public class AddCustomLibraryDialog extends DialogWrapper { public static AddCustomLibraryDialog createDialog(@NotNull CustomLibraryDescription description, final @NotNull Module module, - final ParametrizedRunnable beforeLibraryAdded) { + final ParameterizedRunnable beforeLibraryAdded) { return createDialog(description, LibrariesContainerFactory.createContainer(module), module, null, beforeLibraryAdded); } public static AddCustomLibraryDialog createDialog(CustomLibraryDescription description, final @NotNull LibrariesContainer librariesContainer, final @NotNull Module module, final @Nullable ModifiableRootModel modifiableRootModel, - @Nullable ParametrizedRunnable beforeLibraryAdded) { + @Nullable ParameterizedRunnable beforeLibraryAdded) { return new AddCustomLibraryDialog(description, librariesContainer, module, modifiableRootModel, beforeLibraryAdded); } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/JavadocOrderRootTypeUIFactory.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/JavadocOrderRootTypeUIFactory.java index 95b831ea0703..6a5b19a54672 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/JavadocOrderRootTypeUIFactory.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/JavadocOrderRootTypeUIFactory.java @@ -84,9 +84,11 @@ public class JavadocOrderRootTypeUIFactory implements OrderRootTypeUIFactory { if (versionString != null) { final LanguageLevel level = LanguageLevelUtil.getDefaultLanguageLevel(versionString); if (level == LanguageLevel.JDK_1_5) { - return "http://java.sun.com/j2se/1.5.0/docs/api/"; + return "http://download.oracle.com/javase/1.5.0/docs/api/"; } else if (level == LanguageLevel.JDK_1_6) { - return "http://java.sun.com/j2se/6/docs/api/"; + return "http://download.oracle.com/javase/6/docs/api/"; + } else if (level == LanguageLevel.JDK_1_7) { + return "http://download.oracle.com/javase/7/docs/api/"; } } } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/DefaultInsertHandler.java b/java/java-impl/src/com/intellij/codeInsight/completion/DefaultInsertHandler.java index 1c8c9c4f8613..743f0b1482cc 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/DefaultInsertHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/DefaultInsertHandler.java @@ -65,6 +65,7 @@ public class DefaultInsertHandler extends TemplateInsertHandler implements Clone final boolean needLeftParenth = isToInsertParenth(context, item); final boolean hasParams = needLeftParenth && hasParams(context, item); + final boolean annotation = insertingAnnotation(context, item); if (CompletionUtil.isOverwrite(item, completionChar)) { removeEndOfIdentifier(needLeftParenth && hasParams, context); @@ -106,15 +107,7 @@ public class DefaultInsertHandler extends TemplateInsertHandler implements Clone 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)) { + if (annotation) { // Check if someone inserts annotation class that require @ PsiElement elementAt = file.findElementAt(context.getStartOffset()); final PsiElement parentElement = elementAt != null ? elementAt.getParent():null; @@ -323,7 +316,6 @@ public class DefaultInsertHandler extends TemplateInsertHandler implements Clone case ':': return TailType.CASE_COLON; //? case '<': case '>': - case '#': case '\"': case '[': return TailType.createSimpleTailType(completionChar); } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/FocusInJavadoc.java b/java/java-impl/src/com/intellij/codeInsight/completion/FocusInJavadoc.java new file mode 100644 index 000000000000..95a99a37d912 --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/completion/FocusInJavadoc.java @@ -0,0 +1,35 @@ +/* + * 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; + } +} diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaClassNameCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaClassNameCompletionContributor.java index 2a487a5ae069..0e2cd86abad8 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaClassNameCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaClassNameCompletionContributor.java @@ -17,6 +17,7 @@ package com.intellij.codeInsight.completion; import com.intellij.codeInsight.ExpectedTypeInfo; import com.intellij.codeInsight.ExpectedTypesProvider; +import com.intellij.codeInsight.TailType; import com.intellij.lang.LangBundle; import com.intellij.lang.StdLanguages; import com.intellij.openapi.actionSystem.IdeActions; @@ -32,6 +33,7 @@ import com.intellij.psi.filters.TrueFilter; import com.intellij.psi.filters.classes.ThisOrAnyInnerFilter; import com.intellij.psi.filters.element.ExcludeDeclaredFilter; import com.intellij.psi.filters.types.AssignableFromFilter; +import com.intellij.psi.javadoc.PsiDocTag; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.util.Consumer; @@ -66,8 +68,29 @@ public class JavaClassNameCompletionContributor extends CompletionContributor { return; } - if (completingRawConstructor(context, item) && !JavaCompletionUtil.hasAccessibleInnerClass(item.getObject(), file)) { - ConstructorInsertHandler.insertParentheses(context, item, item.getObject()); + PsiElement position = file.findElementAt(offset); + PsiClass psiClass = item.getObject(); + + if (context.getCompletionChar() == '#') { + context.setLaterRunnable(new Runnable() { + public void run() { + new CodeCompletionHandlerBase(CompletionType.BASIC).invoke(context.getProject(), context.getEditor(), file); + } + }); + TailType.insertChar(context.getEditor(), context.getTailOffset(), '#'); + } + + if (position != null) { + PsiElement parent = position.getParent(); + if (parent instanceof PsiJavaCodeReferenceElement && PsiTreeUtil.getParentOfType(position, PsiDocTag.class) != null) { + if (((PsiJavaCodeReferenceElement)parent).isReferenceTo(psiClass)) { + return; + } + } + } + + if (completingRawConstructor(context, item) && !JavaCompletionUtil.hasAccessibleInnerClass(psiClass, file)) { + ConstructorInsertHandler.insertParentheses(context, item, psiClass); DefaultInsertHandler.addImportForItem(context.getFile(), context.getStartOffset(), item); } else { new DefaultInsertHandler().handleInsert(context, item); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/StaticMembersWeigher.java b/java/java-impl/src/com/intellij/codeInsight/completion/StaticMembersWeigher.java index a152036ff12e..09bad5eecc58 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/StaticMembersWeigher.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/StaticMembersWeigher.java @@ -27,17 +27,13 @@ import org.jetbrains.annotations.Nullable; */ 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(); @@ -55,8 +51,9 @@ public class StaticMembersWeigher extends CompletionWeigher { if (o instanceof PsiField) return 4; } - if (o instanceof PsiClass && ((PsiClass) o).getContainingClass() != null) { - return 3; + if (o instanceof PsiClass) { + if (((PsiClass) o).getContainingClass() != null) return 3; + return 2; } //instance method or field diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/PostHighlightingPass.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/PostHighlightingPass.java index 042abef112cd..5049e9da9235 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/PostHighlightingPass.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/PostHighlightingPass.java @@ -34,6 +34,7 @@ import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection; import com.intellij.codeInspection.ex.InspectionManagerEx; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.codeInspection.unusedImport.UnusedImportLocalInspection; +import com.intellij.codeInspection.unusedParameters.UnusedParametersInspection; import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection; import com.intellij.codeInspection.util.SpecialAnnotationsUtil; import com.intellij.lang.Language; @@ -49,6 +50,7 @@ import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; @@ -172,29 +174,32 @@ public class PostHighlightingPass extends TextEditorHighlightingPass { private void optimizeImportsOnTheFly(@NotNull final Editor editor) { if (myHasRedundantImports || myHasMissortedImports) { - invokeOnTheFlyImportOptimizer(new Runnable() { - public void run() { - if (myProject.isDisposed() || editor.isDisposed()) { - return; - } - OptimizeImportsFix optimizeImportsFix = new OptimizeImportsFix(); - if (optimizeImportsFix.isAvailable(myProject, editor, myFile) && myFile.isWritable()) { - PsiDocumentManager.getInstance(myProject).commitAllDocuments(); + final OptimizeImportsFix optimizeImportsFix = new OptimizeImportsFix(); + if (optimizeImportsFix.isAvailable(myProject, editor, myFile) && myFile.isWritable()) { + invokeOnTheFlyImportOptimizer(new Runnable() { + public void run() { optimizeImportsFix.invoke(myProject, editor, myFile); } - } - }); + }, myFile, editor); + } } } - public static void invokeOnTheFlyImportOptimizer(final Runnable runnable) { + public static void invokeOnTheFlyImportOptimizer(@NotNull final Runnable runnable, @NotNull final PsiFile file, @NotNull final Editor editor) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { + if (file.getProject().isDisposed() || editor.isDisposed()) return; + PsiDocumentManager.getInstance(file.getProject()).commitAllDocuments(); + String beforeText = file.getText(); CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(runnable); } }); + String afterText = file.getText(); + if (Comparing.strEqual(beforeText, afterText)) { + LOG.error("Import optimizer for the '"+file.getVirtualFile().getPath()+"' hasn't optimized any imports. Text:\n"+afterText); + } } }); } @@ -263,6 +268,7 @@ public class PostHighlightingPass extends TextEditorHighlightingPass { return processField((PsiField)parent, identifier, progress); } if (parent instanceof PsiParameter && myUnusedSymbolInspection.PARAMETER) { + if (InspectionManagerEx.isSuppressed(identifier, UnusedParametersInspection.SHORT_NAME)) return null; return processParameter((PsiParameter)parent, progress); } if (parent instanceof PsiMethod && myUnusedSymbolInspection.METHOD) { diff --git a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java index 8580bec1c398..6f56bc39b7f0 100644 --- a/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java +++ b/java/java-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java @@ -807,6 +807,9 @@ public class JavaDocInfoGenerator { " background-color: #eeeeee;" + " margin-bottom: 10px;" + " }" + + " p {" + + " margin: 5px 0;" + + " }" + " " + ""); } diff --git a/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java b/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java index f7c14ed6aeda..4fc3c3cc4224 100644 --- a/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java +++ b/java/java-impl/src/com/intellij/codeInspection/inferNullity/InferNullityAnnotationsAction.java @@ -54,7 +54,7 @@ public class InferNullityAnnotationsAction extends BaseAnalysisAction { private JCheckBox myAnnotateLocalVariablesCb; public InferNullityAnnotationsAction() { - super("Infer nullity", INFER_NULLITY_ANNOTATIONS); + super("Infer Nullity", INFER_NULLITY_ANNOTATIONS); } @Override diff --git a/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspection.java b/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspection.java index 2a44b4603958..73c1821c0a38 100644 --- a/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspection.java @@ -97,6 +97,7 @@ public class JavaDocLocalInspection extends BaseLocalInspectionTool { public boolean IGNORE_DEPRECATED = false; public boolean IGNORE_JAVADOC_PERIOD = true; public boolean IGNORE_DUPLICATED_THROWS = false; + public boolean IGNORE_POINT_TO_ITSELF = false; public String myAdditionalJavadocTags = ""; private static final Logger LOG = Logger.getInstance("com.intellij.codeInspection.javaDoc.JavaDocLocalInspection"); @@ -252,6 +253,14 @@ public class JavaDocLocalInspection extends BaseLocalInspectionTool { } }); add(ignoreDuplicateThrowsCheckBox, gc); + + final JCheckBox ignorePointToItselfCheckBox = new JCheckBox("Ignore javadoc pointing to itself", IGNORE_POINT_TO_ITSELF); + ignorePointToItselfCheckBox.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + IGNORE_POINT_TO_ITSELF = ignorePointToItselfCheckBox.isSelected(); + } + }); + add(ignorePointToItselfCheckBox, gc); } public FieldPanel createAdditionalJavadocTagsPanel(){ @@ -951,16 +960,18 @@ public class JavaDocLocalInspection extends BaseLocalInspectionTool { if (manager.getTagInfo(inlineDocTag.getName()) == null) { checkTagInfo(inspectionManager, null, inlineDocTag, isOnTheFly, problems); } - final PsiDocTagValue value = inlineDocTag.getValueElement(); - if (value != null) { - final PsiReference reference = value.getReference(); - if (reference != null) { - final PsiElement ref = reference.resolve(); - if (ref != null){ - if (PsiTreeUtil.getParentOfType(inlineDocTag, PsiDocCommentOwner.class) == PsiTreeUtil.getParentOfType(ref, PsiDocCommentOwner.class, false)) { - if (nameElement != null) { - problems.add(createDescriptor(nameElement, InspectionsBundle.message("inspection.javadoc.problem.pointing.to.itself"), inspectionManager, - isOnTheFly)); + if (!IGNORE_POINT_TO_ITSELF) { + final PsiDocTagValue value = inlineDocTag.getValueElement(); + if (value != null) { + final PsiReference reference = value.getReference(); + if (reference != null) { + final PsiElement ref = reference.resolve(); + if (ref != null){ + if (PsiTreeUtil.getParentOfType(inlineDocTag, PsiDocCommentOwner.class) == PsiTreeUtil.getParentOfType(ref, PsiDocCommentOwner.class, false)) { + if (nameElement != null) { + problems.add(createDescriptor(nameElement, InspectionsBundle.message("inspection.javadoc.problem.pointing.to.itself"), inspectionManager, + isOnTheFly)); + } } } } diff --git a/java/java-impl/src/com/intellij/codeInspection/unusedParameters/UnusedParametersInspection.java b/java/java-impl/src/com/intellij/codeInspection/unusedParameters/UnusedParametersInspection.java index 2789e3d095ff..72d563db0647 100644 --- a/java/java-impl/src/com/intellij/codeInspection/unusedParameters/UnusedParametersInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/unusedParameters/UnusedParametersInspection.java @@ -40,6 +40,7 @@ import com.intellij.psi.util.PsiModificationTracker; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.changeSignature.ChangeSignatureProcessor; import com.intellij.refactoring.changeSignature.ParameterInfoImpl; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -49,6 +50,8 @@ import java.util.List; public class UnusedParametersInspection extends GlobalJavaInspectionTool { + @NonNls public static final String SHORT_NAME = "UnusedParameters"; + @Nullable public CommonProblemDescriptor[] checkElement(final RefEntity refEntity, final AnalysisScope scope, @@ -204,7 +207,7 @@ public class UnusedParametersInspection extends GlobalJavaInspectionTool { @NotNull public String getShortName() { - return "UnusedParameters"; + return SHORT_NAME; } diff --git a/java/java-impl/src/com/intellij/codeInspection/unusedSymbol/UnusedSymbolLocalInspection.java b/java/java-impl/src/com/intellij/codeInspection/unusedSymbol/UnusedSymbolLocalInspection.java index 74560cdc1e27..4ede61a08dbc 100644 --- a/java/java-impl/src/com/intellij/codeInspection/unusedSymbol/UnusedSymbolLocalInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/unusedSymbol/UnusedSymbolLocalInspection.java @@ -16,35 +16,20 @@ package com.intellij.codeInspection.unusedSymbol; -import com.intellij.ExtensionPoints; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInsight.daemon.QuickFixBundle; import com.intellij.codeInsight.daemon.impl.HighlightInfoType; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInspection.BaseJavaLocalInspectionTool; -import com.intellij.codeInspection.ex.EntryPointsManager; import com.intellij.codeInspection.ex.EntryPointsManagerImpl; import com.intellij.codeInspection.ex.UnfairLocalInspectionTool; -import com.intellij.codeInspection.reference.EntryPoint; import com.intellij.codeInspection.util.SpecialAnnotationsUtil; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.extensions.ExtensionPoint; -import com.intellij.openapi.extensions.ExtensionPointListener; -import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; -import com.intellij.openapi.util.JDOMExternalizableStringList; -import com.intellij.profile.codeInspection.InspectionProfileManager; -import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiModifierListOwner; -import com.intellij.psi.util.PropertyUtil; -import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.ui.UIUtil; -import gnu.trove.THashSet; import org.intellij.lang.annotations.Pattern; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -54,8 +39,6 @@ import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.util.*; -import java.util.List; /** * User: anna @@ -170,13 +153,10 @@ public class UnusedSymbolLocalInspection extends BaseJavaLocalInspectionTool imp public static IntentionAction createQuickFix(final String qualifiedName, String element, Project project) { final EntryPointsManagerImpl entryPointsManager = EntryPointsManagerImpl.getInstance(project); - final ArrayList targetList = new ArrayList(); - targetList.addAll(entryPointsManager.ADDITIONAL_ANNOTATIONS); - targetList.addAll(entryPointsManager.getAdditionalAnnotations()); return SpecialAnnotationsUtil.createAddToSpecialAnnotationsListIntentionAction( QuickFixBundle.message("fix.unused.symbol.injection.text", element, qualifiedName), QuickFixBundle.message("fix.unused.symbol.injection.family"), - targetList, qualifiedName); + entryPointsManager.ADDITIONAL_ANNOTATIONS, qualifiedName); } public static boolean isInjected(final PsiModifierListOwner modifierListOwner) { diff --git a/java/java-impl/src/com/intellij/ide/projectView/impl/PackageViewPane.java b/java/java-impl/src/com/intellij/ide/projectView/impl/PackageViewPane.java index 3069e3852d43..89fd090a2461 100644 --- a/java/java-impl/src/com/intellij/ide/projectView/impl/PackageViewPane.java +++ b/java/java-impl/src/com/intellij/ide/projectView/impl/PackageViewPane.java @@ -19,6 +19,9 @@ */ 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; @@ -27,6 +30,7 @@ import com.intellij.ide.projectView.ViewSettings; 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; @@ -51,13 +55,12 @@ import org.jetbrains.annotations.Nullable; 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); @@ -91,6 +94,12 @@ public final class PackageViewPane extends AbstractProjectViewPSIPane { @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(); } @@ -290,4 +299,30 @@ public final class PackageViewPane extends AbstractProjectViewPSIPane { 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 allElements = Arrays.asList(getSelectedDirectories()); + List validElements = new ArrayList(); + 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(); + } + } + } } diff --git a/java/java-impl/src/com/intellij/psi/impl/smartPointers/AnchorElementInfo.java b/java/java-impl/src/com/intellij/psi/impl/smartPointers/AnchorElementInfo.java index 6cdf6b4d49aa..efaf4626a856 100644 --- a/java/java-impl/src/com/intellij/psi/impl/smartPointers/AnchorElementInfo.java +++ b/java/java-impl/src/com/intellij/psi/impl/smartPointers/AnchorElementInfo.java @@ -115,4 +115,11 @@ class AnchorElementInfo implements SmartPointerElementInfo { return null; } } + + @Override + public void dispose() { + if (myMarker != null) { + myMarker.dispose(); + } + } } diff --git a/java/java-impl/src/com/intellij/psi/impl/smartPointers/ImplicitVariableElementInfoFactory.java b/java/java-impl/src/com/intellij/psi/impl/smartPointers/ImplicitVariableElementInfoFactory.java index e6a6f36bfb42..ad95e90b3b6e 100644 --- a/java/java-impl/src/com/intellij/psi/impl/smartPointers/ImplicitVariableElementInfoFactory.java +++ b/java/java-impl/src/com/intellij/psi/impl/smartPointers/ImplicitVariableElementInfoFactory.java @@ -43,6 +43,10 @@ public class ImplicitVariableElementInfoFactory implements SmartPointerElementIn return null; } + @Override + public void dispose() { + } + @Nullable public Document getDocumentToSynchronize() { return null; diff --git a/java/java-impl/src/com/intellij/psi/impl/smartPointers/ImportListElementInfoFactory.java b/java/java-impl/src/com/intellij/psi/impl/smartPointers/ImportListElementInfoFactory.java index f798857e0346..853a82691117 100644 --- a/java/java-impl/src/com/intellij/psi/impl/smartPointers/ImportListElementInfoFactory.java +++ b/java/java-impl/src/com/intellij/psi/impl/smartPointers/ImportListElementInfoFactory.java @@ -42,6 +42,10 @@ public class ImportListElementInfoFactory implements SmartPointerElementInfoFact return myFile.getImportList(); } + @Override + public void dispose() { + } + public Document getDocumentToSynchronize() { return null; } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiExpressionStatementImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiExpressionStatementImpl.java index e1373dcb0556..de4fd131035d 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiExpressionStatementImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/java/PsiExpressionStatementImpl.java @@ -36,7 +36,7 @@ public class PsiExpressionStatementImpl extends CompositePsiElement implements P public PsiExpression getExpression() { PsiExpression expression = (PsiExpression)SourceTreeToPsiMap.treeElementToPsi(findChildByType(ElementType.EXPRESSION_BIT_SET)); if (expression != null) return expression; - LOG.error("Illegal PSI. Children: " + DebugUtil.psiToString(this, false)); + LOG.error("Illegal PSI: \n" + DebugUtil.psiToString(getParent(), false)); return null; } diff --git a/java/java-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java b/java/java-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java index a712d909d37f..cf95704cc1e7 100644 --- a/java/java-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java +++ b/java/java-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java @@ -197,16 +197,26 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{ 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--; + } } } } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java index 5ffe1cdb733f..ce76aa6d6c23 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java @@ -102,6 +102,8 @@ public class IntroduceConstantHandler extends BaseExpressionToFieldHandler { if (ref instanceof PsiLocalVariable) { localVariable = (PsiLocalVariable)ref; } + } else if (anchorElement instanceof PsiLocalVariable) { + localVariable = (PsiLocalVariable)anchorElement; } if (localVariable == null) { diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldHandler.java index 2be3c0b00098..0b07c76b4088 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldHandler.java @@ -88,11 +88,13 @@ public class IntroduceFieldHandler extends BaseExpressionToFieldHandler { if (ref instanceof PsiLocalVariable) { localVariable = (PsiLocalVariable)ref; } + } else if (anchorElement instanceof PsiLocalVariable) { + localVariable = (PsiLocalVariable)anchorElement; } int occurencesNumber = occurences.length; final boolean currentMethodConstructor = containingMethod != null && containingMethod.isConstructor(); - final boolean allowInitInMethod = (!currentMethodConstructor || !isInSuperOrThis) && anchorElement instanceof PsiStatement; + final boolean allowInitInMethod = (!currentMethodConstructor || !isInSuperOrThis) && anchorElement instanceof PsiLocalVariable; final boolean allowInitInMethodIfAll = (!currentMethodConstructor || !isInSuperOrThis) && anchorElementIfAll instanceof PsiStatement; IntroduceFieldDialog dialog = new IntroduceFieldDialog( project, parentClass, expr, localVariable, @@ -139,7 +141,7 @@ public class IntroduceFieldHandler extends BaseExpressionToFieldHandler { PsiExpression[] occurences, boolean isStatic) { final PsiStatement statement = PsiTreeUtil.getParentOfType(local, PsiStatement.class); - return IntroduceFieldHandler.this.showRefactoringDialog(project, editor, aClass, local.getInitializer(), local.getType(), occurences, statement, statement); + return IntroduceFieldHandler.this.showRefactoringDialog(project, editor, aClass, local.getInitializer(), local.getType(), occurences, local, statement); } }; return localToFieldHandler.convertLocalToField(localVariable, editor); diff --git a/java/java-tests/testData/codeInsight/completion/normalSorting/PreferOwnInnerClasses.java b/java/java-tests/testData/codeInsight/completion/normalSorting/PreferOwnInnerClasses.java new file mode 100644 index 000000000000..bb0f31cccf13 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/normalSorting/PreferOwnInnerClasses.java @@ -0,0 +1,9 @@ +class Foo { + final Yy + + private static class YyyXxx { + + } +} + +class YyyZzz {} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/smartTypeSorting/PrefixOutweighsGenericity.java b/java/java-tests/testData/codeInsight/completion/smartTypeSorting/PrefixOutweighsGenericity.java new file mode 100644 index 000000000000..460e229815aa --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/smartTypeSorting/PrefixOutweighsGenericity.java @@ -0,0 +1,9 @@ +class Foo { + + { + Object o = getUD + } + + final String getUserDataString() {} + final T getUserData(T t) {} +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/style/after15.java b/java/java-tests/testData/codeInsight/completion/style/after15.java index 681bed8c16b8..1ba026a30775 100644 --- a/java/java-tests/testData/codeInsight/completion/style/after15.java +++ b/java/java-tests/testData/codeInsight/completion/style/after15.java @@ -1,6 +1,6 @@ class A{ { String str; - str.toCharArray(); + str.toString(); } } \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/style/after17.java b/java/java-tests/testData/codeInsight/completion/style/after17.java index 3017047611de..6b9c70503bbc 100644 --- a/java/java-tests/testData/codeInsight/completion/style/after17.java +++ b/java/java-tests/testData/codeInsight/completion/style/after17.java @@ -1,7 +1,7 @@ class A{ { final String path = BASE_PATH; - path.toCharArray(); + path.toString(); sdkfjsdkhjfh(); } } \ No newline at end of file diff --git a/java/java-tests/testData/psi/generics22/collect-2.2.jar b/java/java-tests/testData/psi/generics22/collect-2.2.jar new file mode 100644 index 000000000000..a453bbae3dcd Binary files /dev/null and b/java/java-tests/testData/psi/generics22/collect-2.2.jar differ diff --git a/java/java-tests/testData/refactoring/introduceField/afterBeforeNotExist.java b/java/java-tests/testData/refactoring/introduceField/afterBeforeNotExist.java index 1cc3c4c3a539..5f1a526f39a9 100644 --- a/java/java-tests/testData/refactoring/introduceField/afterBeforeNotExist.java +++ b/java/java-tests/testData/refactoring/introduceField/afterBeforeNotExist.java @@ -2,12 +2,12 @@ import org.junit.*; public class T { private int i; - @Test - public void test() { - } - @Before public void setUp() throws Exception { i = 9; } + + @Test + public void test() { + } } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/introduceField/afterBeforeNotExist1.java b/java/java-tests/testData/refactoring/introduceField/afterBeforeNotExist1.java index e5473447eec0..9ad0a3ffd02b 100644 --- a/java/java-tests/testData/refactoring/introduceField/afterBeforeNotExist1.java +++ b/java/java-tests/testData/refactoring/introduceField/afterBeforeNotExist1.java @@ -3,12 +3,12 @@ import org.junit.Test; public class T { private int i; - @Test - public void test() { - } - @Before public void setUp() throws Exception { i = 9; } + + @Test + public void test() { + } } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/introduceField/afterInSetUp.java b/java/java-tests/testData/refactoring/introduceField/afterInSetUp.java index 086f3ed6c4e7..3a13b81ea6f6 100644 --- a/java/java-tests/testData/refactoring/introduceField/afterInSetUp.java +++ b/java/java-tests/testData/refactoring/introduceField/afterInSetUp.java @@ -2,11 +2,11 @@ import junit.framework.TestCase; public class T extends TestCase { private int i; - public void test() { - } - protected void setUp() throws Exception { super.setUp(); i = 9; } + + public void test() { + } } diff --git a/java/java-tests/testData/refactoring/introduceField/afterPublicBaseClassSetUp.java b/java/java-tests/testData/refactoring/introduceField/afterPublicBaseClassSetUp.java index 442bccd8a575..e148221ea414 100644 --- a/java/java-tests/testData/refactoring/introduceField/afterPublicBaseClassSetUp.java +++ b/java/java-tests/testData/refactoring/introduceField/afterPublicBaseClassSetUp.java @@ -9,11 +9,11 @@ class Base extends TestCase { public class T extends Base { private int i; - public void test() { - } - public void setUp() throws Exception { super.setUp(); i = 9; } + + public void test() { + } } diff --git a/java/java-tests/testData/vfs/changes/PsiChangesTest.java b/java/java-tests/testData/vfs/changes/PsiChangesTest.java new file mode 100644 index 000000000000..9eed5b390812 --- /dev/null +++ b/java/java-tests/testData/vfs/changes/PsiChangesTest.java @@ -0,0 +1,13 @@ +public class PsiChangesTest { + private int a; + private int b; + + PsiChangesTest() { + } + + void foo() { + } + + void bar() { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/vfs/changes/PsiChangesTest_changed.java b/java/java-tests/testData/vfs/changes/PsiChangesTest_changed.java new file mode 100644 index 000000000000..d1b63245d7ac --- /dev/null +++ b/java/java-tests/testData/vfs/changes/PsiChangesTest_changed.java @@ -0,0 +1,15 @@ +public class PsiChangesTest { + protected int a; + private int c; + + PsiChangesTest() { + int i = 0; + } + + void foo() { + int i = 0; + } + + void bar2() { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/vfs/changes/results/fields.txt b/java/java-tests/testData/vfs/changes/results/fields.txt new file mode 100644 index 000000000000..db4ece4b6b62 --- /dev/null +++ b/java/java-tests/testData/vfs/changes/results/fields.txt @@ -0,0 +1,3 @@ +a : Modified +b : Deleted +c : Added \ No newline at end of file diff --git a/java/java-tests/testData/vfs/changes/results/methods.txt b/java/java-tests/testData/vfs/changes/results/methods.txt new file mode 100644 index 000000000000..ce935736d151 --- /dev/null +++ b/java/java-tests/testData/vfs/changes/results/methods.txt @@ -0,0 +1,4 @@ +PsiChangesTest : Modified +foo : Modified +bar : Deleted +bar2 : Added diff --git a/java/java-tests/testData/vfs/encoding/UTF16BOM.txt b/java/java-tests/testData/vfs/encoding/UTF16BOM.txt new file mode 100644 index 000000000000..127653fbc516 --- /dev/null +++ b/java/java-tests/testData/vfs/encoding/UTF16BOM.txt @@ -0,0 +1 @@ +ÿþ@8 \ No newline at end of file diff --git a/java/java-tests/testData/vfs/encoding/defaultHtml.html b/java/java-tests/testData/vfs/encoding/defaultHtml.html new file mode 100644 index 000000000000..6c70bcfe4d48 --- /dev/null +++ b/java/java-tests/testData/vfs/encoding/defaultHtml.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/java/java-tests/testData/vfs/encoding/xDefault.xml b/java/java-tests/testData/vfs/encoding/xDefault.xml new file mode 100644 index 000000000000..97f9db629032 --- /dev/null +++ b/java/java-tests/testData/vfs/encoding/xDefault.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/java/java-tests/testData/vfs/encoding/xIbm866.xml b/java/java-tests/testData/vfs/encoding/xIbm866.xml new file mode 100644 index 000000000000..bacdd17750cc --- /dev/null +++ b/java/java-tests/testData/vfs/encoding/xIbm866.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/java/java-tests/testData/vfs/encoding/xNotepadUtf8.xml b/java/java-tests/testData/vfs/encoding/xNotepadUtf8.xml new file mode 100644 index 000000000000..78d324f59dd6 --- /dev/null +++ b/java/java-tests/testData/vfs/encoding/xNotepadUtf8.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/java/java-tests/testData/vfs/encoding/xTrickyProlog.xml b/java/java-tests/testData/vfs/encoding/xTrickyProlog.xml new file mode 100644 index 000000000000..fb023c1d6f2d --- /dev/null +++ b/java/java-tests/testData/vfs/encoding/xTrickyProlog.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/java/java-tests/testData/vfs/encoding/xWin1251.xml b/java/java-tests/testData/vfs/encoding/xWin1251.xml new file mode 100644 index 000000000000..5f7b3df29c6c --- /dev/null +++ b/java/java-tests/testData/vfs/encoding/xWin1251.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/java/java-tests/testData/vfs/findFileByUrl/1.txt b/java/java-tests/testData/vfs/findFileByUrl/1.txt new file mode 100644 index 000000000000..276e7895a0ac --- /dev/null +++ b/java/java-tests/testData/vfs/findFileByUrl/1.txt @@ -0,0 +1 @@ +test text \ No newline at end of file diff --git a/java/java-tests/testData/vfs/findFileByUrl/test.zip b/java/java-tests/testData/vfs/findFileByUrl/test.zip new file mode 100644 index 000000000000..16021fb5aca2 Binary files /dev/null and b/java/java-tests/testData/vfs/findFileByUrl/test.zip differ diff --git a/java/java-tests/testData/vfs/relativePath/subDir/subSubDir/empty.txt b/java/java-tests/testData/vfs/relativePath/subDir/subSubDir/empty.txt new file mode 100644 index 000000000000..013ed0d36bb7 --- /dev/null +++ b/java/java-tests/testData/vfs/relativePath/subDir/subSubDir/empty.txt @@ -0,0 +1 @@ +Empty file \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy index d00fcbdc4c4a..34ad3cf9d0ad 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy @@ -217,4 +217,28 @@ class JavaAutoPopupTest extends CompletionAutoPopupTestCase { assert lookup } + public void testFocusInJavadoc() { + myFixture.configureByText("a.java", """ + /** + * {@link ArrLi} + */ + class Foo {} + """) + type 's' + assert lookup.focused + + } + + public void testPrefixLengthDependentSorting() { + myFixture.addClass("package foo; public class PsiJavaCodeReferenceElement {}") + myFixture.configureByText("a.java", """ + class PsiJavaCodeReferenceElementImpl { + { } + } + """) + type 'PJCR' + assertOrderedEquals myFixture.lookupElementStrings, 'PsiJavaCodeReferenceElement', 'PsiJavaCodeReferenceElementImpl' + + } + } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.java index 92d2147d11da..0f4c06849997 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.java @@ -112,6 +112,10 @@ public class NormalCompletionOrderingTest extends CompletionSortingTestCase { checkPreferredItems(0, "Xxy", "Xxx", "XxxEx", "XxxImpl"); } + public void testPreferOwnInnerClasses() throws Throwable { + checkPreferredItems(0, "YyyXxx", "YyyZzz"); + } + public void testDontDispreferImplsAfterNew() throws Throwable { VfsUtil.saveText(getSourceRoot().createChildDirectory(this, "foo").createChildData(this, "Xxx.java"), "package foo; public interface Xxx {}"); checkPreferredItems(0, "Xxx", "XxxImpl"); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionOrderingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionOrderingTest.java index 941230f43c37..a5744049073d 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionOrderingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionOrderingTest.java @@ -203,6 +203,10 @@ public class SmartTypeCompletionOrderingTest extends CompletionSortingTestCase { checkPreferredItems(0, "Goo", "InnerGoo", "Bar", "AGoo"); } + public void testPrefixOutweighsGenericity() throws Throwable { + checkPreferredItems(0, "getUserData", "getUserDataString"); + } + public void testLocalVariablesOutweighStats() throws Throwable { final LookupImpl lookup = invokeCompletion(BASE_PATH + "/" + getTestName(false) + ".java"); assertPreferredItems(0, "foo", "param", "this", "bar", "goo"); diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java index fbcff73b7c8a..d9d39a9a68bc 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java @@ -72,26 +72,8 @@ public class InspectionProfileTest extends UsefulTestCase { private static Element loadOldStyleProfile() throws IOException, JDOMException { final Document document = JDOMUtil.loadDocument("\n" + - " "); @@ -127,7 +110,7 @@ public class InspectionProfileTest extends UsefulTestCase { private static Element loadProfile() throws IOException, JDOMException { final Document document = JDOMUtil.loadDocument("\n" + - " "); diff --git a/java/java-tests/testSrc/com/intellij/openapi/vfs/DummyFileSystemTest.java b/java/java-tests/testSrc/com/intellij/openapi/vfs/DummyFileSystemTest.java new file mode 100644 index 000000000000..17014f94662b --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/openapi/vfs/DummyFileSystemTest.java @@ -0,0 +1,49 @@ +package com.intellij.openapi.vfs; + +import com.intellij.openapi.application.Result; +import com.intellij.openapi.application.WriteAction; +import com.intellij.openapi.vfs.ex.dummy.DummyFileSystem; +import com.intellij.testFramework.IdeaTestCase; + +public class DummyFileSystemTest extends IdeaTestCase { + DummyFileSystem fs; + + @Override + protected void setUp() throws Exception { + super.setUp(); + fs = new DummyFileSystem(); + } + + public void testDeletionEvents() throws Exception { + final VirtualFile root = fs.createRoot("root"); + VirtualFile f = new WriteAction() { + @Override + protected void run(Result result) throws Throwable { + VirtualFile res = root.createChildData(null, "f"); + result.setResult(res); + } + }.execute().getResultObject(); + + final VirtualFileEvent[] events = new VirtualFileEvent[2]; + fs.addVirtualFileListener(new VirtualFileAdapter() { + @Override + public void fileDeleted(VirtualFileEvent e) { + events[0] = e; + } + + @Override + public void beforeFileDeletion(VirtualFileEvent e) { + events[1] = e; + } + }); + + f.delete(null); + + for (int i = 0; i < 2; i++) { + assertNotNull(events[i]); + assertEquals(f, events[i].getFile()); + assertEquals("f", events[i].getFileName()); + assertEquals(root, events[i].getParent()); + } + } +} diff --git a/java/java-tests/testSrc/com/intellij/openapi/vfs/GetPathPerformanceTest.java b/java/java-tests/testSrc/com/intellij/openapi/vfs/GetPathPerformanceTest.java new file mode 100644 index 000000000000..c67d4baaba67 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/openapi/vfs/GetPathPerformanceTest.java @@ -0,0 +1,42 @@ +package com.intellij.openapi.vfs; + +import com.intellij.testFramework.IdeaTestUtil; +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.testFramework.IdeaTestCase; + +import java.io.File; +import java.io.IOException; + +public class GetPathPerformanceTest extends IdeaTestCase { + public void testGetPath() throws IOException { + File dir = createTempDirectory(); + try { + File subdir1 = new File(dir, "1"); + File subdir2 = new File(dir, "2"); + subdir1.mkdir(); + subdir2.mkdir(); + for (int i = 0; i < 10; ++i) { + new File(subdir1, "" + i).createNewFile(); + new File(subdir2, "" + i).createNewFile(); + } + VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(dir.getPath().replace(File.separatorChar, '/')); + assertNotNull(file); + + final VirtualFile[] children = file.getChildren(); + Runnable runnable = new Runnable() { + @Override + public void run() { + for( int i = 0; i < 1000000; ++i ) { + for( VirtualFile child: children) { + child.getPath(); + } + } + } + }; + IdeaTestUtil.assertTiming("Performance failed", 3000, runnable); + } + finally { + FileUtil.delete(dir); + } + } +} diff --git a/java/java-tests/testSrc/com/intellij/openapi/vfs/JarFileSystemTest.java b/java/java-tests/testSrc/com/intellij/openapi/vfs/JarFileSystemTest.java new file mode 100644 index 000000000000..dc48b51ee662 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/openapi/vfs/JarFileSystemTest.java @@ -0,0 +1,61 @@ +package com.intellij.openapi.vfs; + +import com.intellij.openapi.projectRoots.Sdk; +import com.intellij.openapi.roots.ModuleRootManager; +import com.intellij.openapi.util.SystemInfo; +import com.intellij.testFramework.IdeaTestCase; + +import java.io.File; + +public class JarFileSystemTest extends IdeaTestCase{ + public void testFindFile() throws Exception{ + Sdk jdk = ModuleRootManager.getInstance(myModule).getSdk(); + VirtualFile jdkHome = jdk.getHomeDirectory(); + String rtJarPath = new File(jdkHome.getPath() + "/src.zip").getCanonicalPath().replace(File.separator, "/"); + + VirtualFile file1 = findByPath(rtJarPath + JarFileSystem.JAR_SEPARATOR); + assertTrue(file1.isDirectory()); + + VirtualFile file2 = findByPath(rtJarPath + JarFileSystem.JAR_SEPARATOR + "java"); + assertTrue(file2.isDirectory()); + + VirtualFile file3 = file1.findChild("java"); + assertEquals(file2, file3); + + VirtualFile file4 = findByPath(rtJarPath + JarFileSystem.JAR_SEPARATOR + "java/lang/Object.java"); + assertTrue(!file4.isDirectory()); + + byte[] bytes = file4.contentsToByteArray(); + assertNotNull(bytes); + assertTrue(bytes.length > 10); + } + + public void testMetaInf() throws Exception{ + Sdk jdk = ModuleRootManager.getInstance(myModule).getSdk(); + VirtualFile jdkHome = jdk.getHomeDirectory(); + String rtJarPath = jdkHome.getPath() + "/jre/lib/rt.jar"; + + VirtualFile jarRoot = JarFileSystem.getInstance().findFileByPath(rtJarPath + JarFileSystem.JAR_SEPARATOR); + assertNotNull(jarRoot); + + VirtualFile metaInf = jarRoot.findChild("META-INF"); + assertNotNull(metaInf); + + VirtualFile[] children = metaInf.getChildren(); + assertEquals(1, children.length); + } + + private static VirtualFile findByPath(String path) { + VirtualFile file = JarFileSystem.getInstance().findFileByPath(path); + assertNotNull(file); + final String filePath = file.getPath(); + final String message = "paths are not equal, path1 = " + path + " found: " + filePath; + if (SystemInfo.isFileSystemCaseSensitive) { + assertEquals(message, path, file.getPath()); + } + else { + assertTrue(message, path.equalsIgnoreCase(filePath)); + } + return file; + } +} diff --git a/java/java-tests/testSrc/com/intellij/openapi/vfs/LocalFileSystemTest.java b/java/java-tests/testSrc/com/intellij/openapi/vfs/LocalFileSystemTest.java new file mode 100644 index 000000000000..820ddfd6d8d6 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/openapi/vfs/LocalFileSystemTest.java @@ -0,0 +1,222 @@ +package com.intellij.openapi.vfs; + +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.util.registry.Registry; +import com.intellij.openapi.vfs.impl.win32.Win32LocalFileSystem; +import com.intellij.openapi.vfs.newvfs.ManagingFS; +import com.intellij.testFramework.IdeaTestCase; +import com.intellij.testFramework.IdeaTestUtil; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; + +public class LocalFileSystemTest extends IdeaTestCase{ + private static final String KEY = "filesystem.useNative"; + + public void testChildrenAccessedButNotCached() throws Exception{ + ApplicationManager.getApplication().runWriteAction( + new Runnable() { + @Override + public void run() { + try{ + File dir = createTempDirectory(); + final ManagingFS managingFS = ManagingFS.getInstance(); + + VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(dir.getPath().replace(File.separatorChar, '/')); + assertNotNull(vFile); + assertFalse(managingFS.areChildrenLoaded(vFile)); + assertFalse(managingFS.wereChildrenAccessed(vFile)); + + final File child = new File(dir, "child"); + final boolean created = child.createNewFile(); + assertTrue(created); + + final File subdir = new File(dir, "subdir"); + final boolean subdirCreated = subdir.mkdir(); + assertTrue(subdirCreated); + + final File subChild = new File(subdir, "subdir"); + final boolean subChildCreated = subChild.createNewFile(); + assertTrue(subChildCreated); + + final VirtualFile childVFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(child.getPath().replace(File.separatorChar, '/')); + assertNotNull(childVFile); + assertFalse(managingFS.areChildrenLoaded(vFile)); + assertTrue(managingFS.wereChildrenAccessed(vFile)); + + final VirtualFile subdirVFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(subdir.getPath().replace(File.separatorChar, '/')); + assertNotNull(subdirVFile); + assertFalse(managingFS.areChildrenLoaded(subdirVFile)); + assertFalse(managingFS.wereChildrenAccessed(subdirVFile)); + + assertFalse(managingFS.areChildrenLoaded(vFile)); + assertTrue(managingFS.wereChildrenAccessed(vFile)); + + + vFile.getChildren(); + assertTrue(managingFS.areChildrenLoaded(vFile)); + assertTrue(managingFS.wereChildrenAccessed(vFile)); + assertFalse(managingFS.areChildrenLoaded(subdirVFile)); + assertFalse(managingFS.wereChildrenAccessed(subdirVFile)); + + final VirtualFile subChildVFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(subChild.getPath().replace(File.separatorChar, '/')); + assertNotNull(subChildVFile); + assertTrue(managingFS.areChildrenLoaded(vFile)); + assertTrue(managingFS.wereChildrenAccessed(vFile)); + assertFalse(managingFS.areChildrenLoaded(subdirVFile)); + assertTrue(managingFS.wereChildrenAccessed(subdirVFile)); + } + catch(IOException e){ + LOG.error(e); + } + } + } + ); + } + + public void testRefreshAndFindFile() throws Exception{ + ApplicationManager.getApplication().runWriteAction( + new Runnable() { + @Override + public void run() { + try{ + File dir = createTempDirectory(); + + VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(dir.getPath().replace(File.separatorChar, '/')); + assertNotNull(vFile); + vFile.getChildren(); + + for(int i = 0; i < 100; i++){ + File subdir = new File(dir, "a" + i); + assertTrue(subdir.mkdir()); + } + + File subdir = new File(dir, "aaa"); + assertTrue(subdir.mkdir()); + + VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(subdir.getPath().replace(File.separatorChar, '/')); + assertNotNull(file); + } + catch(IOException e){ + LOG.error(e); + } + } + } + ); + } + + public void testCopyFile() throws Exception{ + ApplicationManager.getApplication().runWriteAction( + new Runnable() { + @Override + public void run() { + try{ + File fromDir = createTempDirectory(); + File toDir = createTempDirectory(); + + VirtualFile fromVDir = LocalFileSystem.getInstance().findFileByPath(fromDir.getPath().replace(File.separatorChar, '/')); + VirtualFile toVDir = LocalFileSystem.getInstance().findFileByPath(toDir.getPath().replace(File.separatorChar, '/')); + assertNotNull(fromVDir); + assertNotNull(toVDir); + final VirtualFile fileToCopy = fromVDir.createChildData(null, "temp_file"); + final byte[] byteContent = {0, 1, 2, 3}; + fileToCopy.setBinaryContent(byteContent); + final String newName = "new_temp_file"; + final VirtualFile copy = fileToCopy.copy(null, toVDir, newName); + assertEquals(newName, copy.getName()); + assertTrue(Arrays.equals(byteContent, copy.contentsToByteArray())); + } + catch(Exception e){ + LOG.error(e); + } + } + } + ); + } + + public void testCopyDir() throws Exception{ + ApplicationManager.getApplication().runWriteAction( + new Runnable() { + @Override + public void run() { + try{ + File fromDir = createTempDirectory(); + File toDir = createTempDirectory(); + + VirtualFile fromVDir = LocalFileSystem.getInstance().findFileByPath(fromDir.getPath().replace(File.separatorChar, '/')); + VirtualFile toVDir = LocalFileSystem.getInstance().findFileByPath(toDir.getPath().replace(File.separatorChar, '/')); + assertNotNull(fromVDir); + assertNotNull(toVDir); + final VirtualFile dirToCopy = fromVDir.createChildDirectory(null, "dir"); + final VirtualFile file = dirToCopy.createChildData(null, "temp_file"); + file.setBinaryContent(new byte[]{0, 1, 2, 3}); + final String newName = "dir"; + final VirtualFile dirCopy = dirToCopy.copy(null, toVDir, newName); + assertEquals(newName, dirCopy.getName()); + IdeaTestUtil.assertDirectoriesEqual(toVDir, fromVDir, null); + } + catch(Exception e){ + LOG.error(e); + } + } + } + ); + } + + public void testGermanLetters() throws Exception{ + final File dirFile = createTempDirectory(); + + final String name = "te\u00dft123123123.txt"; + final File childFile = new File(dirFile, name); + childFile.createNewFile(); + + ApplicationManager.getApplication().runWriteAction( + new Runnable() { + @Override + public void run() { + try{ + final VirtualFile dir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(dirFile); + assertNotNull(dir); + + final VirtualFile child = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(childFile); + assertNotNull(child); + + } + catch(Exception e){ + LOG.error(e); + } + } + } + ); + + + assertTrue(childFile.delete()); + } + + public void _testSymLinks() throws Exception { + ApplicationManager.getApplication().runWriteAction( + new Runnable() { + @Override + public void run() { + boolean b = Registry.get(KEY).asBoolean(); + try{ + Registry.get(KEY).setValue(false); + final VirtualFile dir = LocalFileSystem.getInstance().refreshAndFindFileByPath("C:/Documents and Settings"); + Win32LocalFileSystem system = Win32LocalFileSystem.getWin32Instance(); + system.exists(dir); + String[] strings = system.list(dir); + System.out.println(Arrays.asList(strings)); + } + catch(Exception e){ + fail(e.getMessage()); + } + finally { + Registry.get(KEY).setValue(b); + } + } + } + ); + + } +} diff --git a/java/java-tests/testSrc/com/intellij/openapi/vfs/RefreshChildrenTest.java b/java/java-tests/testSrc/com/intellij/openapi/vfs/RefreshChildrenTest.java new file mode 100644 index 000000000000..dedc483a8e89 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/openapi/vfs/RefreshChildrenTest.java @@ -0,0 +1,67 @@ +package com.intellij.openapi.vfs; + +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.testFramework.IdeaTestCase; + +import java.io.*; + +/** + * @author yole + */ +public class RefreshChildrenTest extends IdeaTestCase { + private File testDir; + + @Override + protected void setUp() throws Exception { + + // the superclass sets tmpdir on every run and cleans up, but we want to do it our way + + String baseTempDir = FileUtil.getTempDirectory(); + testDir = new File(baseTempDir, "RefreshChildrenTest." + getName()); + + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + FileUtil.delete(testDir); + super.tearDown(); + } + + public void testRefreshSeesLatestDirectoryContents() throws Exception { + assertFalse(testDir.exists()); + testDir.mkdir(); + assertTrue(testDir.isDirectory()); + writeFile(testDir, "Foo.java", ""); + + LocalFileSystem local = LocalFileSystem.getInstance(); + VirtualFile virtualDir = local.findFileByIoFile(testDir); + virtualDir.getChildren(); + virtualDir.refresh(false, true); + + checkChildCount(virtualDir, 1); + + writeFile(testDir, "Bar.java", ""); + virtualDir.refresh(false, true); + + checkChildCount(virtualDir, 2); + } + + private void writeFile(File dir, String filename, String contents) throws IOException { + Writer writer = new OutputStreamWriter(new FileOutputStream(new File(dir, filename)), "UTF-8"); + writer.write(contents); + writer.close(); + } + + private void checkChildCount(VirtualFile virtualDir, int expectedCount) { + VirtualFile[] children = virtualDir.getChildren(); + if (children.length != expectedCount) { + System.err.println("children:"); + for (VirtualFile child : children) { + System.err.println(child.getPath()); + } + } + assertEquals(expectedCount, children.length); + } + +} diff --git a/java/java-tests/testSrc/com/intellij/openapi/vfs/VfsUtilTest.java b/java/java-tests/testSrc/com/intellij/openapi/vfs/VfsUtilTest.java new file mode 100644 index 000000000000..a0a9c87401ea --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/openapi/vfs/VfsUtilTest.java @@ -0,0 +1,243 @@ +package com.intellij.openapi.vfs; + +import com.intellij.concurrency.JobUtil; +import com.intellij.openapi.application.Result; +import com.intellij.openapi.application.WriteAction; +import com.intellij.openapi.application.ex.PathManagerEx; +import com.intellij.openapi.progress.ProgressManager; +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.testFramework.IdeaTestCase; +import com.intellij.testFramework.IdeaTestUtil; +import com.intellij.util.Processor; +import com.intellij.util.ui.UIUtil; + +import javax.swing.*; +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +public class VfsUtilTest extends IdeaTestCase { + @Override + protected void runBareRunnable(Runnable runnable) throws Throwable { + runnable.run(); + } + + @Override + protected void setUp() throws Exception { + UIUtil.invokeAndWaitIfNeeded(new Runnable() { + @Override + public void run() { + try { + VfsUtilTest.super.setUp(); + } + catch (Exception e) { + throw new RuntimeException(e); + } + } + }); + } + + @Override + protected void tearDown() throws Exception { + UIUtil.invokeAndWaitIfNeeded(new Runnable() { + @Override + public void run() { + try { + VfsUtilTest.super.tearDown(); + } + catch (Exception e) { + throw new RuntimeException(e); + } + } + }); + } + + public void testFindFileByUrl() throws Exception { + VirtualFile file0; + + // Should not find in jre jars - it creates a lot of VirtualFileImpl! + +// file0 = VfsUtil.findFileByURL(ClassLoader.getSystemResource("java/lang/Object.class")); +// assertNotNull(file0); +// assertFalse(file0.isDirectory()); +// +// file0 = VfsUtil.findFileByURL(ClassLoader.getSystemResource("com/sun")); +// assertNotNull(file0); +// assertTrue(file0.isDirectory()); + + File file1 = new File(PathManagerEx.getTestDataPath()); + file1 = new File(file1, "vfs"); + file1 = new File(file1, "findFileByUrl"); + file0 = VfsUtil.findFileByURL(file1.toURL()); + assertNotNull(file0); + assertTrue(file0.isDirectory()); + final VirtualFile[] children = file0.getChildren(); + List list = new ArrayList(); + final VirtualFileFilter fileFilter = new VirtualFileFilter() { + @Override + public boolean accept(VirtualFile file) { + return IdeaTestUtil.CVS_FILE_FILTER.accept(file) && !file.getName().endsWith(".new"); + } + }; + for (VirtualFile child : children) { + if (fileFilter.accept(child)) { + list.add(child); + } + } + assertEquals(2, list.size()); // "CVS" dir ignored + + File file2 = new File(file1, "test.zip"); + URL url2 = file2.toURL(); + url2 = new URL("jar", "", url2.toExternalForm() + "!/"); + url2 = new URL(url2, "com/intellij/installer"); + url2 = new URL(url2.toExternalForm()); + file0 = VfsUtil.findFileByURL(url2); + assertNotNull(file0); + assertTrue(file0.isDirectory()); + + File file3 = new File(file1, "1.txt"); + file0 = VfsUtil.findFileByURL(file3.toURL()); + String content = VfsUtil.loadText(file0); + assertNotNull(file0); + assertFalse(file0.isDirectory()); + assertEquals(content, "test text"); + } + + public void testRelativePath() throws Exception { + final File root = new File(PathManagerEx.getTestDataPath()); + final File testRoot = new File(new File(root, "vfs"), "relativePath"); + VirtualFile vTestRoot = LocalFileSystem.getInstance().findFileByIoFile(testRoot); + assertNotNull(vTestRoot); + assertTrue(vTestRoot.isDirectory()); + + final File subDir = new File(testRoot, "subDir"); + final VirtualFile vSubDir = LocalFileSystem.getInstance().findFileByIoFile(subDir); + assertNotNull(vSubDir); + + final File subSubDir = new File(subDir, "subSubDir"); + final VirtualFile vSubSubDir = LocalFileSystem.getInstance().findFileByIoFile(subSubDir); + assertNotNull(vSubSubDir); + + assertEquals("subDir", VfsUtil.getRelativePath(vSubDir, vTestRoot, '/')); + assertEquals("subDir/subSubDir", VfsUtil.getRelativePath(vSubSubDir, vTestRoot, '/')); + assertEquals("", VfsUtil.getRelativePath(vTestRoot, vTestRoot, '/')); + } + + public void testAsyncRefresh() throws Throwable { + final Throwable[] ex = {null}; + JobUtil.invokeConcurrentlyUnderProgress(Arrays.asList(new Object[8]), new Processor() { + @Override + public boolean process(Object o) { + try { + doAsyncRefreshTest(); + } + catch (Throwable t) { + ex[0] = t; + } + return true; + } + }, false, ProgressManager.getInstance().getProgressIndicator()); + if (ex[0] != null) throw ex[0]; + } + + private void doAsyncRefreshTest() throws Exception { + int N = 1000; + File temp = new WriteAction() { + @Override + protected void run(Result result) throws Throwable { + File res = createTempDirectory(); + result.setResult(res); + } + }.execute().getResultObject(); + LocalFileSystem fs = LocalFileSystem.getInstance(); + VirtualFile vtemp = fs.findFileByIoFile(temp); + assert vtemp != null; + VirtualFile[] children = new VirtualFile[N]; + + long[] timestamp = new long[N]; + for (int i=0;i< N;i++) { + File file = new File(temp, i + ".txt"); + FileUtil.writeToFile(file, "xxx".getBytes()); + VirtualFile child = fs.findFileByIoFile(file); + assertNotNull(child); + children[i] = child; + timestamp[i] = file.lastModified(); + } + + vtemp.refresh(false,true); + + for (int i=0;i< N;i++) { + File file = new File(temp, i + ".txt"); + assertEquals(timestamp[i], file.lastModified()); + } + + for (int i = 0; i < N; i++) { + File file = new File(temp, i + ".txt"); + VirtualFile child = fs.findFileByIoFile(file); + assertNotNull(child); + + long mod = child.getTimeStamp(); + assertEquals("File:"+child.getPath()+"; mod:"+ new Date(mod)+"; io:"+new File(child.getPath()).lastModified(),timestamp[i], mod); + } + + Thread.sleep(300); + for (int i=0;i< N;i++) { + File file = new File(temp, i + ".txt"); + FileUtil.writeToFile(file, "xxx".getBytes()); + long modified = file.lastModified(); + assertTrue(timestamp[i] != modified); + timestamp[i] = modified; + assertTrue(children[i].getTimeStamp() != modified); + } + + final CountDownLatch latch = new CountDownLatch(N); + for (final VirtualFile child : children) { + child.refresh(true, true, new Runnable() { + @Override + public void run() { + latch.countDown(); + } + }); + } + while (true) { + latch.await(100, TimeUnit.MILLISECONDS); + if (SwingUtilities.isEventDispatchThread()) { + UIUtil.dispatchAllInvocationEvents(); + } + else { + UIUtil.pump(); + } + if (latch.getCount() == 0) break; + } + + for (int i = 0; i < N; i++) { + VirtualFile child = children[i]; + long mod = child.getTimeStamp(); + assertEquals(timestamp[i], mod); + } + } + + public void testFindChildWithTrailingSpace() throws IOException { + File tempDir = new WriteAction() { + @Override + protected void run(Result result) throws Throwable { + File res = createTempDirectory(); + result.setResult(res); + } + }.execute().getResultObject(); + VirtualFile vdir = LocalFileSystem.getInstance().findFileByIoFile(tempDir); + assertNotNull(vdir); + assertTrue(vdir.isDirectory()); + + VirtualFile child = vdir.findChild(" "); + assertNull(child); + + assertEmpty(vdir.getChildren()); + } +} diff --git a/java/java-tests/testSrc/com/intellij/openapi/vfs/VirtualFilePointerTest.java b/java/java-tests/testSrc/com/intellij/openapi/vfs/VirtualFilePointerTest.java new file mode 100644 index 000000000000..10bf9caa9200 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/openapi/vfs/VirtualFilePointerTest.java @@ -0,0 +1,400 @@ +package com.intellij.openapi.vfs; + +import com.intellij.openapi.Disposable; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.application.ex.PathManagerEx; +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.pointers.VirtualFilePointer; +import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener; +import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; +import com.intellij.testFramework.IdeaTestCase; +import com.intellij.testFramework.PlatformTestUtil; +import com.intellij.util.ui.UIUtil; +import org.jetbrains.annotations.NonNls; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; + +/** + * @author dsl + */ +public class VirtualFilePointerTest extends IdeaTestCase { + private VirtualFilePointerManager myVirtualFilePointerManager; + + static class LoggingListener implements VirtualFilePointerListener { + private final ArrayList myLog = new ArrayList(); + + @Override + public void beforeValidityChanged(VirtualFilePointer[] pointers) { + verifyPointersInCorrectState(pointers); + myLog.add(buildMessage("before", pointers)); + } + + private static String buildMessage(@NonNls final String startMsg, VirtualFilePointer[] pointers) { + StringBuilder buffer = new StringBuilder(startMsg); + buffer.append(":"); + for (int i = 0; i < pointers.length; i++) { + VirtualFilePointer pointer = pointers[i]; + final String s = Boolean.toString(pointer.isValid()); + if (i > 0) buffer.append(":"); + buffer.append(s); + } + return buffer.toString(); + } + + @Override + public void validityChanged(VirtualFilePointer[] pointers) { + verifyPointersInCorrectState(pointers); + myLog.add(buildMessage("after", pointers)); + } + + public ArrayList getLog() { + return myLog; + } + } + + public void testDelete() throws Exception { + File tempDirectory = createTempDirectory(); + final File fileToDelete = new File(tempDirectory, "toDelete.txt"); + fileToDelete.createNewFile(); + final LoggingListener fileToDeleteListener = new LoggingListener(); + final VirtualFilePointer fileToDeletePointer = createPointerByFile(fileToDelete, fileToDeleteListener); + assertTrue(fileToDeletePointer.isValid()); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + final VirtualFile virtualFile = getVirtualFile(fileToDelete); + try { + virtualFile.delete(null); + } catch (IOException e) { + fail(); + } + } + }); + assertFalse(fileToDeletePointer.isValid()); + assertEquals("[before:true, after:false]", fileToDeleteListener.getLog().toString()); + myFilesToDelete.add(tempDirectory); + } + + public void testCreate() throws Exception { + final File tempDirectory = createTempDirectory(); + final File fileToCreate = new File(tempDirectory, "toCreate.txt"); + final LoggingListener fileToCreateListener = new LoggingListener(); + final VirtualFilePointer fileToCreatePointer = createPointerByFile(fileToCreate, fileToCreateListener); + assertFalse(fileToCreatePointer.isValid()); + fileToCreate.createNewFile(); + final Runnable postRunnable = new Runnable() { + @Override + public void run() { + assertTrue(fileToCreatePointer.isValid()); + assertEquals("[before:false, after:true]", fileToCreateListener.getLog().toString()); + try { + String expectedUrl = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, fileToCreate.getCanonicalPath().replace(File.separatorChar, '/')); + assertEquals(expectedUrl.toUpperCase(), fileToCreatePointer.getUrl().toUpperCase()); + } catch (IOException e) { + fail(); + } + } + }; + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run () { + VirtualFileManager.getInstance().refresh(false); + final VirtualFile virtualFile = getVirtualFile(tempDirectory); + virtualFile.refresh(false, true); + } + }); + postRunnable.run(); + myFilesToDelete.add(fileToCreate); + myFilesToDelete.add(tempDirectory); + } + + public void testMove() throws Exception { + File tempDirectory = createTempDirectory(); + final File moveTarget = new File(tempDirectory, "moveTarget"); + moveTarget.mkdir(); + final File fileToMove = new File(tempDirectory, "toMove.txt"); + fileToMove.createNewFile(); + + final LoggingListener fileToMoveListener = new LoggingListener(); + final VirtualFilePointer fileToMovePointer = createPointerByFile(fileToMove, fileToMoveListener); + assertTrue(fileToMovePointer.isValid()); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + final VirtualFile virtualFile = getVirtualFile(fileToMove); + assertTrue(virtualFile.isValid()); + final VirtualFile target = getVirtualFile(moveTarget); + assertTrue(target.isValid()); + try { + virtualFile.move(null, target); + } catch (IOException e) { + fail(); + } + } + }); + assertTrue(fileToMovePointer.isValid()); + assertEquals("[]", fileToMoveListener.getLog().toString()); + final File fileAfterMove = new File(moveTarget, fileToMove.getName()); + myFilesToDelete.add(fileAfterMove); + myFilesToDelete.add(moveTarget); + myFilesToDelete.add(tempDirectory); + } + + public void testCreate1() throws Exception { + final File tempDirectory = createTempDirectory(); + final File fileToCreate = new File(tempDirectory, "toCreate1.txt"); + final LoggingListener fileToCreateListener = new LoggingListener(); + final VirtualFilePointer fileToCreatePointer = createPointerByFile(fileToCreate, fileToCreateListener); + assertFalse(fileToCreatePointer.isValid()); + fileToCreate.createNewFile(); + final Runnable postRunnable = new Runnable() { + @Override + public void run() { + assertTrue(fileToCreatePointer.isValid()); + assertEquals("[before:false, after:true]", fileToCreateListener.getLog().toString()); + try { + String expectedUrl = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, fileToCreate.getCanonicalPath().replace(File.separatorChar, '/')); + assertEquals(expectedUrl.toUpperCase(), fileToCreatePointer.getUrl().toUpperCase()); + } catch (IOException e) { + fail(); + } + } + }; + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run () { + VirtualFileManager.getInstance().refresh(false); + final VirtualFile virtualFile = getVirtualFile(tempDirectory); + virtualFile.refresh(false, true); + } + }); + postRunnable.run(); + myFilesToDelete.add(fileToCreate); + myFilesToDelete.add(tempDirectory); + } + + public void testMultipleNotifications() throws Exception { + final File tempDir = createTempDirectory(); + final File file_f1 = new File(tempDir, "f1"); + final File file_f2 = new File(tempDir, "f2"); + final LoggingListener listener = new LoggingListener(); + final VirtualFilePointer pointer_f1 = createPointerByFile(file_f1, listener); + final VirtualFilePointer pointer_f2 = createPointerByFile(file_f2, listener); + assertFalse(pointer_f1.isValid()); + assertFalse(pointer_f2.isValid()); + file_f1.createNewFile(); + file_f2.createNewFile(); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + LocalFileSystem.getInstance().refresh(false); + } + }); + assertEquals("[before:false:false, after:true:true]", listener.getLog().toString()); + myFilesToDelete.add(file_f1); + myFilesToDelete.add(file_f2); + } + + public void testJars() throws Exception { + final File tempDir = createTempDirectory(); + final File jarParent = new File(tempDir, "jarParent"); + jarParent.mkdir(); + final File jar = new File(jarParent, "x.jar"); + final File originalJar = new File(PathManagerEx.getTestDataPath() + "/psi/generics22/collect-2.2.jar".replace('/', File.separatorChar)); + FileUtil.copy(originalJar, jar); + + LocalFileSystem.getInstance().refreshAndFindFileByIoFile(jar); // Make sure we receive events when jar changes + + final VirtualFilePointer[] pointersToWatch = new VirtualFilePointer[2]; + final VirtualFilePointerListener listener = new VirtualFilePointerListener() { + @Override + public void beforeValidityChanged(VirtualFilePointer[] pointers) { + verifyPointersInCorrectState(pointersToWatch); + } + + @Override + public void validityChanged(VirtualFilePointer[] pointers) { + verifyPointersInCorrectState(pointersToWatch); + } + }; + final VirtualFilePointer jarParentPointer = createPointerByFile(jarParent, listener); + final String pathInJar = jar.getPath().replace(File.separatorChar, '/') + JarFileSystem.JAR_SEPARATOR; + final String jarUrl = VirtualFileManager.constructUrl(JarFileSystem.PROTOCOL, + pathInJar); + final VirtualFilePointer jarPointer = myVirtualFilePointerManager.create(jarUrl, myProject, listener); + pointersToWatch[0] = jarParentPointer; + pointersToWatch[1] = jarPointer; + assertTrue(jarParentPointer.isValid()); + assertTrue(jarPointer.isValid()); + + jar.delete(); + jarParent.delete(); + refreshVFS(); + + verifyPointersInCorrectState(pointersToWatch); + assertFalse(jarParentPointer.isValid()); + assertFalse(jarPointer.isValid()); + UIUtil.dispatchAllInvocationEvents(); + + jarParent.mkdir(); + FileUtil.copy(originalJar, jar); + + refreshVFS(); + + verifyPointersInCorrectState(pointersToWatch); + assertTrue(jarParentPointer.isValid()); + assertTrue(jarPointer.isValid()); + UIUtil.dispatchAllInvocationEvents(); + + jar.delete(); + jarParent.delete(); + refreshVFS(); + UIUtil.dispatchAllInvocationEvents(); + + verifyPointersInCorrectState(pointersToWatch); + assertFalse(jarParentPointer.isValid()); + assertFalse(jarPointer.isValid()); + UIUtil.dispatchAllInvocationEvents(); + } + + public void testJars2() throws Exception { + final File tempDir = createTempDirectory(); + final File jarParent = new File(tempDir, "jarParent"); + jarParent.mkdir(); + final File jar = new File(jarParent, "x.jar"); + final File originalJar = new File(PathManagerEx.getTestDataPath() + "/psi/generics22/collect-2.2.jar".replace('/', File.separatorChar)); + FileUtil.copy(originalJar, jar); + + LocalFileSystem.getInstance().refreshAndFindFileByIoFile(jar); // Make sure we receive events when jar changes + + final VirtualFilePointer[] pointersToWatch = new VirtualFilePointer[1]; + final VirtualFilePointerListener listener = new VirtualFilePointerListener() { + @Override + public void beforeValidityChanged(VirtualFilePointer[] pointers) { + verifyPointersInCorrectState(pointersToWatch); + } + + @Override + public void validityChanged(VirtualFilePointer[] pointers) { + verifyPointersInCorrectState(pointersToWatch); + } + }; + final String pathInJar = jar.getPath().replace(File.separatorChar, '/') + JarFileSystem.JAR_SEPARATOR; + final String jarUrl = VirtualFileManager.constructUrl(JarFileSystem.PROTOCOL, + pathInJar); + final VirtualFilePointer jarPointer = myVirtualFilePointerManager.create(jarUrl, myProject, listener); + pointersToWatch[0] = jarPointer; + assertTrue(jarPointer.isValid()); + + jar.delete(); + refreshVFS(); + + verifyPointersInCorrectState(pointersToWatch); + assertFalse(jarPointer.isValid()); + UIUtil.dispatchAllInvocationEvents(); + + jarParent.mkdir(); + FileUtil.copy(originalJar, jar); + + refreshVFS(); + + verifyPointersInCorrectState(pointersToWatch); + assertTrue(jarPointer.isValid()); + UIUtil.dispatchAllInvocationEvents(); + + jar.delete(); + refreshVFS(); + UIUtil.dispatchAllInvocationEvents(); + + verifyPointersInCorrectState(pointersToWatch); + assertFalse(jarPointer.isValid()); + UIUtil.dispatchAllInvocationEvents(); + } + + private static void refreshVFS() { + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + VirtualFileManager.getInstance().refresh(false); + } + }); + UIUtil.dispatchAllInvocationEvents(); + } + + private static void verifyPointersInCorrectState(VirtualFilePointer[] pointers) { + for (VirtualFilePointer pointer : pointers) { + final VirtualFile file = pointer.getFile(); + assertTrue(file == null || file.isValid()); + } + } + + private VirtualFilePointer createPointerByFile(final File file, final VirtualFilePointerListener fileListener) throws IOException { + final VirtualFile[] vFile = new VirtualFile[1]; + final String url = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, file.getCanonicalPath().replace(File.separatorChar, '/')); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + vFile[0] = VirtualFileManager.getInstance().refreshAndFindFileByUrl(url); + } + }); + final VirtualFilePointer fileToDeletePointer; + if (vFile[0] == null) { + fileToDeletePointer = myVirtualFilePointerManager.create(url, myProject, fileListener); + } + else { + fileToDeletePointer = myVirtualFilePointerManager.create(vFile[0], myProject, fileListener); + } + return fileToDeletePointer; + } + + public void testFilePointerUpdate() throws Exception { + final File tempDir = createTempDirectory(); + final File file_f1 = new File(tempDir, "f1"); + + final VirtualFilePointer pointer_f1 = createPointerByFile(file_f1, null); + + assertFalse(pointer_f1.isValid()); + + file_f1.createNewFile(); + + doVfsRefresh(); + + assertTrue(pointer_f1.isValid()); + + file_f1.delete(); + + doVfsRefresh(); + assertFalse(pointer_f1.isValid()); + } + + public void testContainerDeletePerformance() throws Exception { + PlatformTestUtil.assertTiming("", 3000, new Runnable() { + @Override + public void run() { + Disposable parent = Disposer.newDisposable(); + for (int i = 0; i < 10000; i++) { + myVirtualFilePointerManager.createContainer(parent); + } + Disposer.dispose(parent); + } + }); + } + + private static void doVfsRefresh() { + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + LocalFileSystem.getInstance().refresh(false); + } + }); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + myVirtualFilePointerManager = VirtualFilePointerManager.getInstance(); + } +} diff --git a/java/java-tests/testSrc/com/intellij/openapi/vfs/changes/PsiChangeTrackerTest.java b/java/java-tests/testSrc/com/intellij/openapi/vfs/changes/PsiChangeTrackerTest.java new file mode 100644 index 000000000000..cc7cfce098de --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/openapi/vfs/changes/PsiChangeTrackerTest.java @@ -0,0 +1,96 @@ +package com.intellij.openapi.vfs.changes; + +import com.intellij.openapi.application.ex.PathManagerEx; +import com.intellij.psi.util.PsiFilter; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.vcs.FileStatus; +import com.intellij.openapi.vcs.changes.PsiChangeTracker; +import com.intellij.openapi.vfs.LocalFileSystem; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.*; +import com.intellij.testFramework.IdeaTestCase; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Konstantin Bulenkov + */ +public class PsiChangeTrackerTest extends IdeaTestCase { + private PsiFile myOriginalFile; + private PsiFile myChangedFile; + + @Override + protected void setUp() throws Exception { + super.setUp(); + final VirtualFile testRoot = getTestRoot(); + final VirtualFile child = testRoot.findChild("PsiChangesTest.java"); + assert child != null : "Can't find PsiChangesTest.java"; + final PsiFile original = this.getPsiManager().findFile(child); + assert original != null : "Can't create PsiFile from VirtualFile " + child.getName(); + myOriginalFile = original; + + final VirtualFile changedFile = testRoot.findChild("PsiChangesTest_changed.java"); + assert changedFile != null : "Can't find PsiChangesTest_changed.java"; + + myChangedFile = PsiFileFactory.getInstance(myProject) + .createFileFromText(new String(changedFile.contentsToByteArray()), myOriginalFile); + assert myChangedFile != null : "Can't create PsiFile from " + changedFile.getPath(); + } + + public void testMethods() throws Exception { + doTest(new PsiFilter(PsiMethod.class)); + } + + public void testFields() throws Exception { + doTest(new PsiFilter(PsiField.class)); + } + + private void doTest(PsiFilter filter) throws IOException { + final Map map = PsiChangeTracker.getElementsChanged(myChangedFile, myOriginalFile, filter); + final Map changes = convert(map); + final Map expected = getExpectedResults(); + assert expected.equals(changes) : "Changes are not equal \n Expected:\n" + expected + "\nFound:\n" + changes; + } + + private static Map convert(Map map) { + final Map result = new HashMap(); + for (T key : map.keySet()) { + final String newKey; + if (key instanceof PsiMember) { + newKey = ((PsiMember)key).getName(); + } else { + newKey = key.getText(); + } + result.put(newKey, map.get(key).getText()); + } + return result; + } + + private Map getExpectedResults() throws IOException { + final String resultFileName = getTestName(true) + ".txt"; + final VirtualFile resultsDir = getTestRoot().findChild("results"); + assert resultsDir != null : "Can't find results dir"; + final VirtualFile result = resultsDir.findChild(resultFileName); + assert result != null : "File not found " + resultsDir.getPath() + "/" + resultFileName; + String res = new String(result.contentsToByteArray()); + final Map map = new HashMap(); + for (String s : res.replace("\r\n", "\n").split("\n")) { + if (!StringUtil.isEmptyOrSpaces(s)) { + final String[] strings = s.split(":"); + map.put(strings[0].trim(), strings[1].trim()); + } + } + return map; + } + + protected static VirtualFile getTestRoot() { + final File root = new File(PathManagerEx.getTestDataPath()); + final File testRoot = new File(new File(root, "vfs"), "changes"); + final VirtualFile ioFile = LocalFileSystem.getInstance().findFileByIoFile(testRoot); + assert ioFile != null : "Can't find directory vfs/changes"; + return ioFile; + } +} diff --git a/java/openapi/src/com/intellij/psi/CommonClassNames.java b/java/openapi/src/com/intellij/psi/CommonClassNames.java index af3c4d67de3b..ecee6767d3a1 100644 --- a/java/openapi/src/com/intellij/psi/CommonClassNames.java +++ b/java/openapi/src/com/intellij/psi/CommonClassNames.java @@ -30,6 +30,7 @@ public interface CommonClassNames { @NonNls String JAVA_LANG_RUNTIME_EXCEPTION = "java.lang.RuntimeException"; @NonNls String JAVA_LANG_ENUM = "java.lang.Enum"; @NonNls String JAVA_LANG_ITERABLE = "java.lang.Iterable"; + @NonNls String JAVA_UTIL_ITERATOR = "java.util.Iterator"; @NonNls String JAVA_LANG_DEPRECATED = "java.lang.Deprecated"; @NonNls String JAVA_LANG_ANNOTATION_INHERITED = "java.lang.annotation.Inherited"; diff --git a/java/testFramework/src/com/intellij/testFramework/fixtures/impl/JavaCodeInsightTestFixtureImpl.java b/java/testFramework/src/com/intellij/testFramework/fixtures/impl/JavaCodeInsightTestFixtureImpl.java index 03ac938431a5..363caf601ddf 100644 --- a/java/testFramework/src/com/intellij/testFramework/fixtures/impl/JavaCodeInsightTestFixtureImpl.java +++ b/java/testFramework/src/com/intellij/testFramework/fixtures/impl/JavaCodeInsightTestFixtureImpl.java @@ -15,6 +15,8 @@ */ package com.intellij.testFramework.fixtures.impl; +import com.intellij.openapi.application.Result; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.ProjectScope; @@ -49,12 +51,17 @@ public class JavaCodeInsightTestFixtureImpl extends CodeInsightTestFixtureImpl i return psiClass; } - private PsiClass addClass(@NonNls String rootPath, @NotNull @NonNls final String classText) throws IOException { + private PsiClass addClass(@NonNls final String rootPath, @NotNull @NonNls final String classText) throws IOException { final PsiClass aClass = ((PsiJavaFile)PsiFileFactory.getInstance(getProject()).createFileFromText("a.java", classText)).getClasses()[0]; final String qName = aClass.getQualifiedName(); assert qName != null; - final PsiFile psiFile = addFileToProject(rootPath, qName.replace('.', '/') + ".java", classText); + final PsiFile psiFile = new WriteCommandAction(getProject()) { + @Override + protected void run(Result result) throws Throwable { + result.setResult(addFileToProject(rootPath, qName.replace('.', '/') + ".java", classText)); + } + }.execute().getResultObject(); return ((PsiJavaFile)psiFile).getClasses()[0]; } diff --git a/platform/icons/src/actions/check_16.png b/platform/icons/src/actions/check_16.png new file mode 100644 index 000000000000..f08996325520 Binary files /dev/null and b/platform/icons/src/actions/check_16.png differ diff --git a/platform/lang-api/src/com/intellij/codeInspection/ProblemsHolder.java b/platform/lang-api/src/com/intellij/codeInspection/ProblemsHolder.java index 42c38ab7626f..801d47e345a8 100644 --- a/platform/lang-api/src/com/intellij/codeInspection/ProblemsHolder.java +++ b/platform/lang-api/src/com/intellij/codeInspection/ProblemsHolder.java @@ -174,8 +174,7 @@ public class ProblemsHolder { @Nullable public ProblemDescriptor[] getResultsArray() { - final List problems = myProblems; - myProblems = null; + final List problems = getResults(); return problems == null ? null : problems.toArray(new ProblemDescriptor[problems.size()]); } diff --git a/platform/lang-api/src/com/intellij/lang/parameterInfo/ParameterInfoUtils.java b/platform/lang-api/src/com/intellij/lang/parameterInfo/ParameterInfoUtils.java index 38461c9dcf82..4b570cb3c2a7 100644 --- a/platform/lang-api/src/com/intellij/lang/parameterInfo/ParameterInfoUtils.java +++ b/platform/lang-api/src/com/intellij/lang/parameterInfo/ParameterInfoUtils.java @@ -20,6 +20,7 @@ import com.intellij.lang.ASTNode; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; +import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.text.CharArrayUtil; @@ -34,10 +35,15 @@ import java.util.Set; public class ParameterInfoUtils { public static final String DEFAULT_PARAMETER_CLOSE_CHARS = ",){}"; - public static T findParentOfType (PsiFile file, int offset, Class parentClass) { + public static @Nullable T findParentOfType (PsiFile file, int offset, Class parentClass) { PsiElement element = file.findElementAt(offset); if (element == null) return null; - return PsiTreeUtil.getParentOfType(element, parentClass); + + T parentOfType = PsiTreeUtil.getParentOfType(element, parentClass); + if (element instanceof PsiWhiteSpace) { + parentOfType = PsiTreeUtil.getParentOfType(PsiTreeUtil.prevLeaf(element), parentClass); + } + return parentOfType; } public static int getCurrentParameterIndex(ASTNode argList, int offset, IElementType delimiterType) { diff --git a/platform/lang-api/src/com/intellij/psi/ReferenceRange.java b/platform/lang-api/src/com/intellij/psi/ReferenceRange.java index f079c906fdfd..2ac202ecb1ae 100644 --- a/platform/lang-api/src/com/intellij/psi/ReferenceRange.java +++ b/platform/lang-api/src/com/intellij/psi/ReferenceRange.java @@ -59,12 +59,12 @@ public class ReferenceRange { public static boolean containsOffsetInElement(PsiReference ref, int offset) { if (ref instanceof MultiRangeReference) { for (TextRange range : ((MultiRangeReference)ref).getRanges()) { - if (range.contains(offset)) return true; + if (range.containsOffset(offset)) return true; } return false; } - return ref.getRangeInElement().contains(offset); + return ref.getRangeInElement().containsOffset(offset); } public static boolean containsRangeInElement(PsiReference ref, TextRange rangeInElement) { diff --git a/platform/lang-api/src/com/intellij/psi/stubs/LightStubBuilder.java b/platform/lang-api/src/com/intellij/psi/stubs/LightStubBuilder.java index 989ddf531e16..8708107450d3 100644 --- a/platform/lang-api/src/com/intellij/psi/stubs/LightStubBuilder.java +++ b/platform/lang-api/src/com/intellij/psi/stubs/LightStubBuilder.java @@ -15,13 +15,14 @@ */ package com.intellij.psi.stubs; -import com.intellij.lang.FileASTNode; -import com.intellij.lang.LighterAST; -import com.intellij.lang.LighterASTNode; +import com.intellij.lang.*; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.psi.PsiFile; import com.intellij.psi.StubBuilder; import com.intellij.psi.tree.IElementType; +import com.intellij.psi.tree.IFileElementType; import com.intellij.psi.tree.ILightStubFileElementType; import gnu.trove.TIntStack; @@ -34,15 +35,23 @@ public class LightStubBuilder implements StubBuilder { @Override public StubElement buildStubTree(final PsiFile file) { - final FileASTNode node = file.getNode(); - assert node != null; - - if (!(node.getElementType() instanceof ILightStubFileElementType)) { - LOG.error("File is not of ILightStubFileElementType: " + file); + final FileType fileType = file.getFileType(); + if (!(fileType instanceof LanguageFileType)) { + LOG.error("File is not of LanguageFileType: " + fileType + ", " + file); return null; } - final ILightStubFileElementType type = (ILightStubFileElementType)node.getElementType(); + final Language language = ((LanguageFileType)fileType).getLanguage(); + final IFileElementType contentType = LanguageParserDefinitions.INSTANCE.forLanguage(language).getFileNodeType(); + if (!(contentType instanceof ILightStubFileElementType)) { + LOG.error("File is not of ILightStubFileElementType: " + contentType + ", " + file); + return null; + } + + final FileASTNode node = file.getNode(); + assert node != null : file; + + final ILightStubFileElementType type = (ILightStubFileElementType)contentType; final LighterAST tree = new LighterAST(node.getCharTable(), type.parseContentsLight(node)); final StubElement rootStub = createStubForFile(file, tree); buildStubTree(tree, tree.getRoot(), rootStub); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java index 952d526dfe78..924ed2bd50d0 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java @@ -402,7 +402,9 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler { LOG.assertTrue(fileCopy.findElementAt(offset) == insertedElement, "wrong offset"); final TextRange range = insertedElement.getTextRange(); - LOG.assertTrue(range.substring(fileCopy.getText()).equals(insertedElement.getText()), "wrong text"); + if (!range.substring(fileCopy.getText()).equals(insertedElement.getText())) { + LOG.error("wrong text: copy='" + fileCopy.getText() + "'; element='" + insertedElement.getText() + "'"); + } return new CompletionParameters(insertedElement, fileCopy.getOriginalFile(), myCompletionType, offset, invocationCount); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java index 1098fcf0f15a..6f2acf672514 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java @@ -273,7 +273,8 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement private boolean isOutdated() { if (!myDisposed) { - LOG.assertTrue(this == CompletionServiceImpl.getCompletionService().getCurrentCompletion()); + CompletionProgressIndicator current = CompletionServiceImpl.getCompletionService().getCurrentCompletion(); + LOG.assertTrue(this == current, current); } return myDisposed || myEditor.isDisposed() || getProject().isDisposed(); } @@ -327,6 +328,8 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement } public void liveAfterDeath(@Nullable final LightweightHint hint) { + assert myDisposed; + if (myModifiersReleased || ApplicationManager.getApplication().isUnitTestMode()) { return; } @@ -391,10 +394,14 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement } myLookup.show(); + //todo remove these assertions before X release + if (!ApplicationManager.getApplication().isUnitTestMode()) { + LOG.assertTrue(myLookup.isVisible()); + } } myLookup.refreshUi(); if (!ApplicationManager.getApplication().isUnitTestMode()) { - LOG.assertTrue(myLookup.isVisible()); + LOG.assertTrue(myLookup.isVisible(), "really?"); } hideAutopopupIfMeaningless(); } @@ -453,8 +460,9 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement if (hideLookup) { LookupManager.getInstance(getProject()).hideActiveLookup(); } + } else { + assert myDisposed; } - } private void finishCompletionProcess() { @@ -479,6 +487,7 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement private void cleanup() { assert ApplicationManager.getApplication().isDispatchThread(); + assert myDisposed; myHint = null; myRestorePrefix = null; unregisterItself(); @@ -607,6 +616,7 @@ public class CompletionProgressIndicator extends ProgressIndicatorBase implement } public void rememberDocumentState() { + assert myDisposed; if (myModifiersReleased) { return; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/PrefixMatchingWeigher.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/PrefixMatchingWeigher.java index c106d8c771a6..1d2b74f65354 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/PrefixMatchingWeigher.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/PrefixMatchingWeigher.java @@ -35,8 +35,7 @@ public class PrefixMatchingWeigher extends CompletionWeigher { final String prefixHumps = StringUtil.capitalsOnly(prefix); final String itemHumps = StringUtil.capitalsOnly(lookupString); - if (itemHumps.equals(prefixHumps)) return 20; - if (itemHumps.startsWith(prefixHumps)) return 10; + if (itemHumps.startsWith(prefixHumps)) return 100 - itemHumps.length(); if (lookupString.startsWith(prefix)) return 5; if (StringUtil.startsWithIgnoreCase(lookupString, prefix)) return 1; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java index 99364f20f93d..475cce0629b2 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java @@ -170,7 +170,8 @@ public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzer implements JDOMEx @NotNull Document document, @NotNull TextEditor textEditor, @NotNull int[] toIgnore, - boolean canChangeDocument) { + boolean canChangeDocument, + @Nullable Runnable callbackWhileWaiting) { Application application = ApplicationManager.getApplication(); application.assertIsDispatchThread(); assert !application.isWriteAccessAllowed(); @@ -191,16 +192,18 @@ public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzer implements JDOMEx final List passes = highlighter.getPasses(toIgnore); HighlightingPass[] array = passes.toArray(new HighlightingPass[passes.size()]); - final DaemonProgressIndicator progress = new DaemonProgressIndicator(); + final DaemonProgressIndicator progress = createUpdateProgress(); progress.setDebug(true); - progress.start(); myPassExecutorService.submitPasses(Collections.singletonMap((FileEditor)textEditor, array), progress, Job.DEFAULT_PRIORITY); try { while (progress.isRunning()) { if (progress.isCanceled() && progress.isRunning()) { // write action sneaked in the AWT. restart waitForTermination(); - return runPasses(file, document, textEditor, toIgnore, canChangeDocument); + return runPasses(file, document, textEditor, toIgnore, canChangeDocument,callbackWhileWaiting); + } + if (callbackWhileWaiting != null) { + callbackWhileWaiting.run(); } progress.waitFor(100); try { @@ -678,23 +681,25 @@ public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzer implements JDOMEx // cancel all after calling createPasses() since there are perverts {@link com.intellij.util.xml.ui.DomUIFactoryImpl} who are changing PSI there cancelUpdateProgress(true, "Cancel by alarm"); myAlarm.cancelAllRequests(); - DaemonProgressIndicator progress; - synchronized (DaemonCodeAnalyzerImpl.this) { - progress = new DaemonProgressIndicator() { - @Override - public void stopIfRunning() { - super.stopIfRunning(); - myProject.getMessageBus().syncPublisher(DAEMON_EVENT_TOPIC).daemonFinished(); - } - }; - progress.start(); - myUpdateProgress = progress; - } + DaemonProgressIndicator progress = createUpdateProgress(); myPassExecutorService.submitPasses(passes, progress, Job.DEFAULT_PRIORITY); } }; } + private synchronized DaemonProgressIndicator createUpdateProgress() { + DaemonProgressIndicator progress = new DaemonProgressIndicator() { + @Override + public void stopIfRunning() { + super.stopIfRunning(); + myProject.getMessageBus().syncPublisher(DAEMON_EVENT_TOPIC).daemonFinished(); + } + }; + progress.start(); + myUpdateProgress = progress; + return progress; + } + public boolean canChangeFileSilently(PsiFileSystemItem file) { return myDaemonListeners.canChangeFileSilently(file); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonListeners.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonListeners.java index 7c020d84aa7d..dbe80edbfb88 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonListeners.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonListeners.java @@ -328,30 +328,19 @@ class DaemonListeners implements Disposable { } private class MyApplicationListener extends ApplicationAdapter { + private boolean myDaemonWasRunning; + public void beforeWriteActionStart(Object action) { - if (!myDaemonCodeAnalyzer.isRunning()) return; // we'll restart in writeActionFinished() - if (LOG.isDebugEnabled()) { - LOG.debug("cancelling code highlighting by write action:" + action); - } - if (containsDocumentWorthBothering(action)) { - stopDaemon(true); - } + myDaemonWasRunning = myDaemonCodeAnalyzer.isRunning(); + if (!myDaemonWasRunning) return; // we'll restart in writeActionFinished() + stopDaemon(true); } public void writeActionFinished(Object action) { - if (containsDocumentWorthBothering(action)) { + if (myDaemonWasRunning) { stopDaemon(true); } } - - private boolean containsDocumentWorthBothering(Object action) { - if (isUnderIgnoredAction(action)) return false; - DocumentRunnable currentWriteAction = action instanceof DocumentRunnable ? (DocumentRunnable)action - : ApplicationManager.getApplication().getCurrentWriteAction(DocumentRunnable.class); - if (currentWriteAction == null) return true; - Document document = currentWriteAction.getDocument(); - return worthBothering(document, currentWriteAction.getProject()); - } } private class MyCommandListener extends CommandAdapter { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/FileStatusMap.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/FileStatusMap.java index d89fb0377d99..c67285dcf5bb 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/FileStatusMap.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/FileStatusMap.java @@ -26,7 +26,6 @@ import com.intellij.openapi.diagnostic.Logger; 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.TextRange; import com.intellij.psi.PsiDocumentManager; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java index ab001ac96da3..0a1a558886b4 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/LocalInspectionsPass.java @@ -37,6 +37,7 @@ import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.TextAttributesKey; +import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.keymap.KeymapUtil; @@ -106,17 +107,34 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass InspectionProfileWrapper customProfile = file.getUserData(InspectionProfileWrapper.KEY); myProfileWrapper = customProfile == null ? InspectionProjectProfileManager.getInstance(myProject).getProfileWrapper() : customProfile; mySeverityRegistrar = ((SeverityProvider)myProfileWrapper.getInspectionProfile().getProfileManager()).getSeverityRegistrar(); + LOG.assertTrue(mySeverityRegistrar != null); // initial guess setProgressLimit(300 * 2); } protected void collectInformationWithProgress(final ProgressIndicator progress) { - if (!HighlightLevelUtil.shouldInspect(myFile)) return; - final InspectionManagerEx iManager = (InspectionManagerEx)InspectionManager.getInstance(myProject); - final InspectionProfileWrapper profile = myProfileWrapper; - final List tools = DumbService.getInstance(myProject).filterByDumbAwareness(getInspectionTools(profile)); - inspect(tools, iManager, true, true, true, progress); + try { + if (!HighlightLevelUtil.shouldInspect(myFile)) return; + final InspectionManagerEx iManager = (InspectionManagerEx)InspectionManager.getInstance(myProject); + final InspectionProfileWrapper profile = myProfileWrapper; + final List tools = DumbService.getInstance(myProject).filterByDumbAwareness(getInspectionTools(profile)); + inspect(tools, iManager, true, true, true, progress); + } + finally { + disposeDescriptors(); + } + } + + private void disposeDescriptors() { + for (List list : result.values()) { + for (InspectionResult inspectionResult : list) { + for (ProblemDescriptor pd: inspectionResult.foundProblems) { + ((ProblemDescriptorImpl)pd).dispose(); + } + } + } + result.clear(); } public void doInspectInBatch(final InspectionManagerEx iManager, List toolWrappers, boolean ignoreSuppressed) { @@ -202,8 +220,26 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass final LocalInspectionToolSession session = new LocalInspectionToolSession(myFile, myStartOffset, myEndOffset); List> init = new ArrayList>(); - visitPriorityElementsAndInit(tools, iManager, isOnTheFly, ignoreSuppressed, indicator, inside, session, init); - visitRestElementsAndCleanup(tools,iManager,isOnTheFly,ignoreSuppressed, indicator, outside, session, init); + boolean finished = false; + try { + visitPriorityElementsAndInit(tools, iManager, isOnTheFly, ignoreSuppressed, indicator, inside, session, init); + visitRestElementsAndCleanup(tools,iManager,isOnTheFly,ignoreSuppressed, indicator, outside, session, init); + finished = true; + } + finally { + if (!finished) { + synchronized (init) { + for (Trinity trinity : init) { + List results = trinity.second.getResults(); + if (results != null) { + for (ProblemDescriptor pd : results) { + ((ProblemDescriptorImpl)pd).dispose(); + } + } + } + } + } + } indicator.checkCanceled(); @@ -357,7 +393,9 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass boolean isFileLevel = element instanceof PsiFile && textRange.equals(element.getTextRange()); final HighlightSeverity severity = highlightInfoType.getSeverity(element); - return new HighlightInfo(mySeverityRegistrar.getTextAttributesBySeverity(severity), highlightInfoType, textRange.getStartOffset(), textRange.getEndOffset(), message, toolTip, + TextAttributes attributes = mySeverityRegistrar.getTextAttributesBySeverity(severity); + return new HighlightInfo(attributes, highlightInfoType, textRange.getStartOffset(), + textRange.getEndOffset(), message, toolTip, severity, problemDescriptor.isAfterEndOfLine(), null, isFileLevel); } @@ -513,7 +551,8 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass List editables = ilManager.intersectWithAllEditableFragments(file, new TextRange(info.startOffset, info.endOffset)); for (TextRange editable : editables) { TextRange hostRange = ((DocumentWindow)documentRange).injectedToHost(editable); - HighlightInfo patched = HighlightInfo.createHighlightInfo(info.type, psiElement, hostRange.getStartOffset(), hostRange.getEndOffset(), info.description, info.toolTip); + HighlightInfo patched = HighlightInfo.createHighlightInfo(info.type, psiElement, hostRange.getStartOffset(), + hostRange.getEndOffset(), info.description, info.toolTip); if (patched != null) { registerQuickFixes(tool, descriptor, patched, emptyActionRegistered); outInfos.add(patched); @@ -553,8 +592,10 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass return highlightInfo; } - private static void registerQuickFixes(final LocalInspectionTool tool, final ProblemDescriptor descriptor, - final HighlightInfo highlightInfo, final Set emptyActionRegistered) { + private static void registerQuickFixes(final LocalInspectionTool tool, + final ProblemDescriptor descriptor, + final HighlightInfo highlightInfo, + final Set emptyActionRegistered) { final HighlightDisplayKey key = HighlightDisplayKey.find(tool.getShortName()); boolean needEmptyAction = true; final QuickFix[] fixes = descriptor.getFixes(); @@ -572,7 +613,7 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass needEmptyAction = false; } if (((ProblemDescriptorImpl)descriptor).getEnforcedTextAttributes() != null) { - needEmptyAction = false; + needEmptyAction = false; } if (needEmptyAction && emptyActionRegistered.add(new TextRange(highlightInfo.fixStartOffset, highlightInfo.fixEndOffset))) { EmptyIntentionAction emptyIntentionAction = new EmptyIntentionAction(tool.getDisplayName()); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java index bce7959a8501..1ee2b413a854 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java @@ -209,6 +209,7 @@ public class ShowIntentionsPass extends TextEditorHighlightingPass { if (place != null) { List enableDisableIntentionAction = new ArrayList(); enableDisableIntentionAction.add(new IntentionHintComponent.EnableDisableIntentionAction(action)); + enableDisableIntentionAction.add(new IntentionHintComponent.EditIntentionSettingsAction(action)); intentions.intentionsToShow.add(new HighlightInfo.IntentionActionDescriptor(action, enableDisableIntentionAction, null)); } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java index 83e7544cdc50..d764365fce9f 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationComponent.java @@ -21,6 +21,7 @@ import com.intellij.codeInsight.hint.ElementLocationUtil; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.codeInsight.hint.HintUtil; import com.intellij.ide.actions.ExternalJavaDocAction; +import com.intellij.ide.ui.UISettings; import com.intellij.lang.documentation.CompositeDocumentationProvider; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.lang.documentation.ExternalDocumentationHandler; @@ -132,6 +133,12 @@ public class DocumentationComponent extends JPanel implements Disposable { } super.processKeyEvent(e); } + + @Override + protected void paintComponent(Graphics g) { + UISettings.setupAntialiasing(g); + super.paintComponent(g); + } }; myText = ""; myEditorPane.setEditable(false); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java index 890e15da0981..2cd30bfbe867 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java @@ -61,7 +61,7 @@ public class CodeFoldingManagerImpl extends CodeFoldingManager implements Projec myProject = project; project.getMessageBus().connect().subscribe(DocumentBulkUpdateListener.TOPIC, new DocumentBulkUpdateListener.Adapter() { public void updateStarted(final Document doc) { - resetFoldingInfo(doc); //TODO RangeMarkers tree convert + resetFoldingInfo(doc); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/EditorFoldingInfo.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/EditorFoldingInfo.java index f5e9f16a1052..e7460e1abe13 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/EditorFoldingInfo.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/EditorFoldingInfo.java @@ -24,6 +24,7 @@ import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.SmartPsiElementPointer; +import com.intellij.psi.impl.smartPointers.SmartPointerEx; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -36,6 +37,7 @@ public class EditorFoldingInfo { private final Map> myFoldRegionToSmartPointerMap = new THashMap>(); + @NotNull public static EditorFoldingInfo get(@NotNull Editor editor) { EditorFoldingInfo info = editor.getUserData(KEY); if (info == null){ @@ -82,15 +84,18 @@ public class EditorFoldingInfo { } public void dispose() { + for(FoldRegion region:myFoldRegionToSmartPointerMap.keySet()) { + SmartPsiElementPointer pointer = myFoldRegionToSmartPointerMap.get(region); + ((SmartPointerEx)pointer).dispose(); + region.dispose(); + } myFoldRegionToSmartPointerMap.clear(); } public static void resetInfo(final Editor editor) { EditorFoldingInfo info = editor.getUserData(KEY); if (info != null) { - for(FoldRegion region:info.myFoldRegionToSmartPointerMap.keySet()) { - region.dispose(); - } + info.dispose(); } editor.putUserData(KEY, null); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/FoldingActionGroup.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/FoldingActionGroup.java deleted file mode 100644 index 1a139fcb1870..000000000000 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/actions/FoldingActionGroup.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.intellij.codeInsight.folding.impl.actions; - -import com.intellij.openapi.actionSystem.*; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.ex.FoldingModelEx; -import com.intellij.openapi.project.DumbAware; - -public class FoldingActionGroup extends DefaultActionGroup implements DumbAware { - public FoldingActionGroup() { - super(); - } - - public void update(AnActionEvent event){ - Presentation presentation = event.getPresentation(); - DataContext dataContext = event.getDataContext(); - - Editor editor = PlatformDataKeys.EDITOR.getData(dataContext); - if (editor == null){ - presentation.setVisible(false); - return; - } - - FoldingModelEx foldingModel = (FoldingModelEx)editor.getFoldingModel(); - presentation.setVisible(foldingModel.isFoldingEnabled()); - } -} \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java index ddf8ab8d7d85..9e8b2c3a1f89 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java @@ -25,6 +25,7 @@ import com.intellij.codeInsight.hint.PriorityQuestionAction; import com.intellij.codeInsight.hint.ScrollAwareHint; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.impl.config.IntentionManagerSettings; +import com.intellij.codeInsight.intention.impl.config.IntentionSettingsConfigurable; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.IdeActions; @@ -33,6 +34,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.VisualPosition; import com.intellij.openapi.keymap.KeymapUtil; +import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.JBPopupListener; @@ -489,4 +491,49 @@ public class IntentionHintComponent extends JPanel implements Disposable, Scroll return getText(); } } + + public static class EditIntentionSettingsAction implements IntentionAction { + private String myFamilyName; + + public EditIntentionSettingsAction(IntentionAction action) { + myFamilyName = action.getFamilyName(); + } + + @NotNull + @Override + public String getText() { + return "Edit intention settings"; + } + + @NotNull + @Override + public String getFamilyName() { + return getText(); + } + + @Override + public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { + return true; + } + + @Override + public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { + final IntentionSettingsConfigurable configurable = new IntentionSettingsConfigurable(); + ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() { + @Override + public void run() { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + configurable.selectIntention(myFamilyName); + } + }); + } + }); + } + + @Override + public boolean startInWriteAction() { + return false; + } + } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsConfigurable.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsConfigurable.java index d49c42b3994a..f9ebfb90b722 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsConfigurable.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsConfigurable.java @@ -103,4 +103,7 @@ public class IntentionSettingsConfigurable extends BaseConfigurable implements S return HELP_ID; } + public void selectIntention(String familyName) { + myPanel.selectIntention(familyName); + } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsPanel.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsPanel.java index 70fbf86759a4..ecf39f78ba11 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsPanel.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsPanel.java @@ -147,6 +147,10 @@ public class IntentionSettingsPanel implements MasterDetails { myIntentionDescriptionPanel.dispose(); } + public void selectIntention(String familyName) { + myIntentionSettingsTree.selectIntention(familyName); + } + private static boolean isIntentionAccepted(IntentionActionMetaData metaData, @NonNls String filter, boolean forceInclude, final List> keySetList, final HashSet quoted) { if (StringUtil.containsIgnoreCase(metaData.getFamily(), filter)) { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java index 33c42af31fa1..a3a674d7b80a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/config/IntentionSettingsTree.java @@ -189,6 +189,14 @@ public abstract class IntentionSettingsTree { treeModel.nodeChanged(root); } + public void selectIntention(String familyName) { + final CheckedTreeNode child = findChildRecursively(getRoot(), familyName); + if (child != null) { + final TreePath path = new TreePath(child.getPath()); + TreeUtil.selectPath(myTree, path); + } + } + private static List sort(final List intentionsToShow) { List copy = new ArrayList(intentionsToShow); Collections.sort(copy, new Comparator() { @@ -244,6 +252,28 @@ public abstract class IntentionSettingsTree { return found.get(); } + private static CheckedTreeNode findChildRecursively(CheckedTreeNode node, final String name) { + final Ref found = new Ref(); + visitChildren(node, new CheckedNodeVisitor() { + public void visit(CheckedTreeNode node) { + if (found.get() != null) return; + final Object userObject = node.getUserObject(); + if (userObject instanceof IntentionActionMetaData) { + String text = getNodeText(node); + if (name.equals(text)) { + found.set(node); + } + } else { + final CheckedTreeNode child = findChildRecursively(node, name); + if (child != null) { + found.set(child); + } + } + } + }); + return found.get(); + } + private static String getNodeText(CheckedTreeNode node) { final Object userObject = node.getUserObject(); String text; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java index 7c5a9fdf31fc..f9761622f173 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java @@ -476,7 +476,7 @@ public class LookupImpl extends LightweightHint implements Lookup, Disposable { JComponent internalComponent = myEditor.getContentComponent(); final JRootPane rootPane = editorComponent.getRootPane(); if (rootPane == null) { - LOG.error(myArranger); + LOG.error(myArranger + "; " + myEditor.isDisposed()); } JLayeredPane layeredPane = rootPane.getLayeredPane(); Point layeredPanePoint=SwingUtilities.convertPoint(internalComponent,location, layeredPane); @@ -712,6 +712,9 @@ public class LookupImpl extends LightweightHint implements Lookup, Disposable { public Rectangle getCurrentItemBounds(){ int index = myList.getSelectedIndex(); + if (index < 0) { + LOG.error("No selected element, size=" + myList.getModel().getSize() + "; items" + getItems()); + } Rectangle itmBounds = myList.getCellBounds(index, index); if (itmBounds == null){ LOG.error("No bounds for " + index + "; size=" + myList.getModel().getSize()); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java index 5596b57a2795..8ff39549d323 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java @@ -985,8 +985,8 @@ public class TemplateState implements Disposable { RangeMarker rangeMarker = null; if (endSegmentNumber >= 0) { int endVarOffset = mySegments.getSegmentStart(endSegmentNumber); - PsiElement marker = CodeStyleManagerImpl.insertNewLineIndentMarker(file, endVarOffset); - if (marker != null) rangeMarker = myDocument.createRangeMarker(marker.getTextRange()); + TextRange range = CodeStyleManagerImpl.insertNewLineIndentMarker(file, myDocument, endVarOffset); + if (range != null) rangeMarker = myDocument.createRangeMarker(range); } int startOffset = rangeMarkerToReformat != null ? rangeMarkerToReformat.getStartOffset() : myTemplateRange.getStartOffset(); int endOffset = rangeMarkerToReformat != null ? rangeMarkerToReformat.getEndOffset() : myTemplateRange.getEndOffset(); diff --git a/platform/lang-impl/src/com/intellij/codeInspection/actions/GotoInspectionModel.java b/platform/lang-impl/src/com/intellij/codeInspection/actions/GotoInspectionModel.java index a7e878941c44..d073bf3f8eb0 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/actions/GotoInspectionModel.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/actions/GotoInspectionModel.java @@ -22,12 +22,8 @@ import com.intellij.codeInspection.ex.ScopeToolState; import com.intellij.ide.IdeBundle; import com.intellij.ide.util.gotoByName.SimpleChooseByNameModel; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Comparing; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.util.ArrayUtil; -import org.apache.oro.text.regex.*; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.*; @@ -35,11 +31,7 @@ import java.util.*; /** * @author Konstantin Bulenkov */ -public class GotoInspectionModel extends SimpleChooseByNameModel {//implements CustomMatcherModel { - private String myPattern; - - private Pattern myCompiledPattern; - private final PatternMatcher myMatcher = new Perl5Matcher(); +public class GotoInspectionModel extends SimpleChooseByNameModel { private final Map myToolNames = new HashMap(); private final Map> myGroupNames = new HashMap>(); private final Map myToolShortNames = new HashMap(); @@ -48,7 +40,7 @@ public class GotoInspectionModel extends SimpleChooseByNameModel {//implements C public GotoInspectionModel(Project project) { - super(project, IdeBundle.message("prompt.goto.inspection.enter.name"), null); //TODO help ID + super(project, IdeBundle.message("prompt.goto.inspection.enter.name"), "goto.inspection.help.id"); final InspectionProfileImpl rootProfile = (InspectionProfileImpl)InspectionProfileManager.getInstance().getRootProfile(); for (ScopeToolState state : rootProfile.getAllTools()) { final InspectionProfileEntry tool = state.getTool(); @@ -69,7 +61,6 @@ public class GotoInspectionModel extends SimpleChooseByNameModel {//implements C final Set nameIds = new HashSet(); nameIds.addAll(myToolNames.keySet()); nameIds.addAll(myGroupNames.keySet()); - //nameIds.addAll(myToolShortNames.keySet()); myNames = ArrayUtil.toStringArray(nameIds); } @@ -105,141 +96,4 @@ public class GotoInspectionModel extends SimpleChooseByNameModel {//implements C } return null; } - - private List findEntries(String name) { - final List result = new ArrayList(); - InspectionProfileEntry e = myToolNames.get(name); - if (e != null) { - result.add(e); - } - //e = myToolShortNames.get(name); - //if (e != null) { - // result.add(e); - //} - final Set entrySet = myGroupNames.get(name); - if (entrySet != null) { - result.addAll(entrySet); - } - return result; - } - - public boolean matches(@NotNull final String name, @NotNull final String pattern) { - for (InspectionProfileEntry entry : findEntries(name)) { - final String toolName = entry.getDisplayName(); - final String id = entry.getShortName(); - final String group = entry.getGroupDisplayName(); - final Pattern compiledPattern = getPattern(pattern); - if (myMatcher.matches(toolName, compiledPattern) - || myMatcher.matches(id, compiledPattern) - || myMatcher.matches(group, compiledPattern)) { - return true; - } - } - - return false; - } - - @NotNull - private Pattern getPattern(String pattern) { - if (!Comparing.strEqual(pattern, myPattern)) { - myCompiledPattern = null; - myPattern = pattern; - } - if (myCompiledPattern == null) { - boolean allowToLower = true; - final int eol = pattern.indexOf('\n'); - if (eol != -1) { - pattern = pattern.substring(0, eol); - } - if (pattern.length() >= 80) { - pattern = pattern.substring(0, 80); - } - - final @NonNls StringBuffer buffer = new StringBuffer(); - - if (containsOnlyUppercaseLetters(pattern)) { - allowToLower = false; - } - - if (allowToLower) { - buffer.append(".*"); - } - - boolean firstIdentifierLetter = true; - for (int i = 0; i < pattern.length(); i++) { - final char c = pattern.charAt(i); - if (Character.isLetterOrDigit(c)) { - // This logic allows to use uppercase letters only to catch the name like PDM for PsiDocumentManager - if (Character.isUpperCase(c) || Character.isDigit(c)) { - - if (!firstIdentifierLetter) { - buffer.append("[^A-Z]*"); - } - - buffer.append("["); - buffer.append(c); - if (allowToLower || i == 0) { - buffer.append('|'); - buffer.append(Character.toLowerCase(c)); - } - buffer.append("]"); - } - else if (Character.isLowerCase(c)) { - buffer.append('['); - buffer.append(c); - buffer.append('|'); - buffer.append(Character.toUpperCase(c)); - buffer.append(']'); - } - else { - buffer.append(c); - } - - firstIdentifierLetter = false; - } - else if (c == '*') { - buffer.append(".*"); - firstIdentifierLetter = true; - } - else if (c == '.') { - buffer.append("\\."); - firstIdentifierLetter = true; - } - else if (c == ' ') { - buffer.append("[^A-Z]*\\ "); - firstIdentifierLetter = true; - } - else { - firstIdentifierLetter = true; - // for standard RegExp engine - // buffer.append("\\u"); - // buffer.append(Integer.toHexString(c + 0x20000).substring(1)); - - // for OROMATCHER RegExp engine - buffer.append("\\x"); - buffer.append(Integer.toHexString(c + 0x20000).substring(3)); - } - } - - buffer.append(".*"); - - - try { - myCompiledPattern = new Perl5Compiler().compile(buffer.toString()); - } - catch (MalformedPatternException e) { - //do nothing - } - } - - return myCompiledPattern; - } - - private static boolean containsOnlyUppercaseLetters(String s) { - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c != '*' && c != ' ' && !Character.isUpperCase(c)) return false; - } - return true; - } } diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/ProblemDescriptorImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/ProblemDescriptorImpl.java index 52ffb45c8a74..b9e746fa4d4e 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/ProblemDescriptorImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/ProblemDescriptorImpl.java @@ -26,6 +26,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.pom.Navigatable; import com.intellij.psi.*; +import com.intellij.psi.impl.smartPointers.SmartPointerEx; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; @@ -40,7 +41,6 @@ public class ProblemDescriptorImpl extends CommonProblemDescriptorImpl implement @NotNull private final SmartPsiElementPointer myStartSmartPointer; @Nullable private final SmartPsiElementPointer myEndSmartPointer; - private final ProblemHighlightType myHighlightType; private Navigatable myNavigatable; private final boolean myAfterEndOfLine; @@ -66,7 +66,10 @@ public class ProblemDescriptorImpl extends CommonProblemDescriptorImpl implement this(startElement, endElement, descriptionTemplate, fixes, highlightType, isAfterEndOfLine, rangeInElement, true, hintAction, onTheFly); } - public ProblemDescriptorImpl(@NotNull PsiElement startElement, @NotNull PsiElement endElement, String descriptionTemplate, LocalQuickFix[] fixes, + public ProblemDescriptorImpl(@NotNull PsiElement startElement, + @NotNull PsiElement endElement, + String descriptionTemplate, + LocalQuickFix[] fixes, ProblemHighlightType highlightType, boolean isAfterEndOfLine, final TextRange rangeInElement, @@ -191,4 +194,9 @@ public class ProblemDescriptorImpl extends CommonProblemDescriptorImpl implement public boolean showTooltip() { return myShowTooltip; } + + public void dispose() { + ((SmartPointerEx)myStartSmartPointer).dispose(); + if (myEndSmartPointer != null) ((SmartPointerEx)myEndSmartPointer).dispose(); + } } diff --git a/platform/lang-impl/src/com/intellij/diagnostic/logging/EditLogPatternDialog.java b/platform/lang-impl/src/com/intellij/diagnostic/logging/EditLogPatternDialog.java index 726411df9a39..f1756e4159b7 100644 --- a/platform/lang-impl/src/com/intellij/diagnostic/logging/EditLogPatternDialog.java +++ b/platform/lang-impl/src/com/intellij/diagnostic/logging/EditLogPatternDialog.java @@ -81,4 +81,9 @@ public class EditLogPatternDialog extends DialogWrapper { return myFilePattern.getText(); } + + @Override + protected String getHelpId() { + return "reference.run.configuration.edit.logfile.aliases"; + } } diff --git a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleBase.java b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleBase.java index 3f2759d4482e..03ada5f46c0f 100644 --- a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleBase.java +++ b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConsoleBase.java @@ -491,10 +491,9 @@ public abstract class LogConsoleBase extends AdditionalTabComponent implements L public void run() { if (myReader == null) return; - while (myRunning) { - final Runnable runnable = new Runnable() { - public void run() { - myAlarm.cancelAllRequests(); + final Runnable runnable = new Runnable() { + public void run() { + if (myRunning) { try { int i = 0; while (i++ < 1000) { @@ -510,9 +509,10 @@ public abstract class LogConsoleBase extends AdditionalTabComponent implements L LOG.error(e); } } - }; - myAlarm.addRequest(runnable, 200); - } + myAlarm.addRequest(this, 100); + } + }; + myAlarm.addRequest(runnable, 10); } public void startRunning() { diff --git a/platform/lang-impl/src/com/intellij/execution/actions/RunConfigurationAction.java b/platform/lang-impl/src/com/intellij/execution/actions/RunConfigurationAction.java index b2d0d9eceb4f..2ce07c7525c7 100644 --- a/platform/lang-impl/src/com/intellij/execution/actions/RunConfigurationAction.java +++ b/platform/lang-impl/src/com/intellij/execution/actions/RunConfigurationAction.java @@ -29,8 +29,10 @@ import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.Key; +import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.impl.IdeFrameImpl; import com.intellij.util.IJSwingUtilities; +import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -42,14 +44,14 @@ public class RunConfigurationAction extends ComboBoxAction implements DumbAware private static final Key BUTTON_KEY = Key.create("COMBOBOX_BUTTON"); public void actionPerformed(final AnActionEvent e) { - final IdeFrameImpl ideFrame = findFrame(e.getData(PlatformDataKeys.CONTEXT_COMPONENT)); - final ComboBoxButton button = (ComboBoxButton)ideFrame.getRootPane().getClientProperty(BUTTON_KEY); + final IdeFrame ideFrame = findFrame(e.getData(PlatformDataKeys.CONTEXT_COMPONENT)); + final ComboBoxButton button = (ComboBoxButton)ideFrame.getComponent().getRootPane().getClientProperty(BUTTON_KEY); if (button == null || !button.isShowing()) return; button.showPopup(); } - private static IdeFrameImpl findFrame(final Component component) { - return IJSwingUtilities.findParentOfType(component, IdeFrameImpl.class); + private static IdeFrame findFrame(final Component component) { + return UIUtil.getParentOfType(IdeFrame.class, component); } public void update(final AnActionEvent e) { @@ -112,9 +114,9 @@ public class RunConfigurationAction extends ComboBoxAction implements DumbAware return new ComboBoxButton(presentation) { public void addNotify() { super.addNotify(); //To change body of overriden methods use Options | File Templates.; - final IdeFrameImpl frame = findFrame(this); + final IdeFrame frame = findFrame(this); LOG.assertTrue(frame != null); - frame.getRootPane().putClientProperty(BUTTON_KEY, this); + frame.getComponent().getRootPane().putClientProperty(BUTTON_KEY, this); } }; } diff --git a/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java b/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java index 4b9a4b34f958..bc2768702e63 100644 --- a/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java @@ -369,14 +369,19 @@ public class LanguageConsoleImpl implements Disposable, TypeSafeDataProvider { //offset can be changed after text trimming after insert due to buffer constraints appendToHistoryDocument(history, text); int offset = history.getTextLength() - text.length(); - final HighlighterIterator iterator = consoleEditor.getHighlighter().createIterator(0); + final int localStartOffset = textRange.getStartOffset(); + final HighlighterIterator iterator = consoleEditor.getHighlighter().createIterator(localStartOffset); + final int localEndOffset = textRange.getEndOffset(); while (!iterator.atEnd()) { - final int localOffset = textRange.getStartOffset(); - final int start = Math.max(iterator.getStart(), localOffset) - localOffset; - final int end = Math.min(iterator.getEnd(), textRange.getEndOffset()) - localOffset; - markupModel.addRangeHighlighter(start + offset, end + offset, HighlighterLayer.SYNTAX, iterator.getTextAttributes(), - HighlighterTargetArea.EXACT_RANGE); - + final int itStart = iterator.getStart(); + if (itStart > localEndOffset) break; + final int itEnd = iterator.getEnd(); + if (itEnd >= localStartOffset) { + final int start = Math.max(itStart, localStartOffset) - localStartOffset + offset; + final int end = Math.min(itEnd, localEndOffset) - localStartOffset + offset; + markupModel.addRangeHighlighter(start, end, HighlighterLayer.SYNTAX, iterator.getTextAttributes(), + HighlighterTargetArea.EXACT_RANGE); + } iterator.advance(); } if (myDoSaveErrorsToHistory) { diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java index c9f9fc957879..e7dca1cf1eb4 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/ConsoleViewImpl.java @@ -28,7 +28,6 @@ import com.intellij.ide.CommonActionsManager; import com.intellij.ide.OccurenceNavigator; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; -import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.command.CommandProcessor; @@ -43,7 +42,6 @@ import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.ex.EditorEx; -import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; import com.intellij.openapi.editor.ex.FoldingModelEx; import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.highlighter.EditorHighlighter; @@ -196,6 +194,11 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo public int getLength() { return endOffset - startOffset; } + + @Override + public String toString() { + return contentType + "[" + startOffset + ";" + endOffset + "]"; + } } private final Project myProject; @@ -347,6 +350,7 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo } myDeferredTypes.clear(); myDeferredUserInput = new StringBuffer(); + myDeferredTokens.clear(); myHyperlinks.clear(); myTokens.clear(); if (myEditor == null) return; @@ -613,7 +617,6 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo } private static void addToken(int length, ConsoleViewContentType contentType, List tokens) { - boolean needNew = true; int startOffset = 0; if (!tokens.isEmpty()) { final TokenInfo lastToken = tokens.get(tokens.size() - 1); @@ -1623,9 +1626,52 @@ public class ConsoleViewImpl extends JPanel implements ConsoleView, ObservableCo } @Override - public void setSelected(AnActionEvent e, boolean state) { + public void setSelected(AnActionEvent e, final boolean state) { super.setSelected(e, state); - EditorSettingsExternalizable.getInstance().setUseSoftWraps(myEditor.getSettings().isUseSoftWraps(), SoftWrapAppliancePlaces.CONSOLE); + + final String placeholder = myCommandLineFolding.getPlaceholder(0); + if (state && placeholder == null) { + return; + } + + final FoldingModel foldingModel = myEditor.getFoldingModel(); + FoldRegion[] foldRegions = foldingModel.getAllFoldRegions(); + Runnable foldTask = null; + + final int endFoldRegionOffset = myEditor.getDocument().getLineEndOffset(0); + Runnable addCollapsedFoldRegionTask = new Runnable() { + @Override + public void run() { + FoldRegion foldRegion = foldingModel.addFoldRegion(0, endFoldRegionOffset, placeholder == null ? "..." : placeholder); + if (foldRegion != null) { + foldRegion.setExpanded(false); + } + } + }; + if (foldRegions.length <= 0) { + if (!state) { + return; + } + foldTask = addCollapsedFoldRegionTask; + } + else { + final FoldRegion foldRegion = foldRegions[0]; + if (foldRegion.getStartOffset() == 0 && foldRegion.getEndOffset() == endFoldRegionOffset) { + foldTask = new Runnable() { + @Override + public void run() { + foldRegion.setExpanded(!state); + } + }; + } + else if (state) { + foldTask = addCollapsedFoldRegionTask; + } + } + + if (foldTask != null) { + foldingModel.runBatchFoldingOperation(foldTask); + } } }; final AnAction autoScrollToTheEndAction = new ScrollToTheEndToolbarAction() { diff --git a/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java b/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java index ae4dc897502a..8a40e421ec57 100644 --- a/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java +++ b/platform/lang-impl/src/com/intellij/execution/runners/AbstractConsoleRunnerWithHistory.java @@ -33,10 +33,13 @@ import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.WriteCommandAction; +import com.intellij.openapi.editor.CaretModel; +import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.IconLoader; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; @@ -46,12 +49,13 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; +import java.awt.event.KeyEvent; import java.util.List; /** * @author oleg - * This class provides basic functionality for running consoles. - * It launches extrnal process and handles line input with history + * This class provides basic functionality for running consoles. + * It launches external process and handles line input with history */ public abstract class AbstractConsoleRunnerWithHistory { private final Project myProject; @@ -222,12 +226,42 @@ public abstract class AbstractConsoleRunnerWithHistory { } }; - final AnAction historyNextAction = ConsoleHistoryModel.createHistoryAction(myHistory, true, historyProcessor); - final AnAction historyPrevAction = ConsoleHistoryModel.createHistoryAction(myHistory, false, historyProcessor); - historyNextAction.getTemplatePresentation().setVisible(false); - historyPrevAction.getTemplatePresentation().setVisible(false); + final EditorEx consoleEditor = languageConsole.getConsoleEditor(); + final Document document = consoleEditor.getDocument(); + final CaretModel caretModel = consoleEditor.getCaretModel(); + final AnAction upAction = new AnAction() { + @Override + public void actionPerformed(final AnActionEvent e) { + final int lineNumber = consoleEditor.getDocument().getLineNumber(caretModel.getOffset()); + if (lineNumber > 0){ + caretModel.moveCaretRelatively(0, -1, false, consoleEditor.getSelectionModel().hasBlockSelection(), true); + } else { + if (myHistory.hasHistory(true)) { + historyProcessor.process(e, myHistory.getHistoryNext()); + } + } + } + }; + final AnAction downAction = new AnAction() { + @Override + public void actionPerformed(final AnActionEvent e) { + final int lineNumber = document.getLineNumber(caretModel.getOffset()); + if (lineNumber < document.getLineCount() - 1 && !StringUtil.isEmptyOrSpaces(document.getText().substring(caretModel.getOffset()))){ + caretModel.moveCaretRelatively(0, 1, false, consoleEditor.getSelectionModel().hasBlockSelection(), true); + } else { + if (myHistory.hasHistory(false)) { + historyProcessor.process(e, myHistory.getHistoryPrev()); + } + } + } + }; - return new ConsoleExecutionActions(runAction, historyNextAction, historyPrevAction); + upAction.getTemplatePresentation().setVisible(false); + downAction.getTemplatePresentation().setVisible(false); + upAction.registerCustomShortcutSet(KeyEvent.VK_UP, 0, null); + downAction.registerCustomShortcutSet(KeyEvent.VK_DOWN, 0, null); + + return new ConsoleExecutionActions(runAction, downAction, upAction); } @NotNull diff --git a/platform/lang-impl/src/com/intellij/find/FindUtil.java b/platform/lang-impl/src/com/intellij/find/FindUtil.java index 07cd7b0d9442..e793312958bf 100644 --- a/platform/lang-impl/src/com/intellij/find/FindUtil.java +++ b/platform/lang-impl/src/com/intellij/find/FindUtil.java @@ -60,7 +60,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; -import java.awt.event.FocusAdapter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -581,7 +580,6 @@ public class FindUtil { HighlighterLayer.SELECTION + 1, selectionAttributes, HighlighterTargetArea.EXACT_RANGE); MyListener listener = new MyListener(editor, segmentHighlighter); - editor.getContentComponent().addFocusListener(listener); caretModel.addCaretListener(listener); } else { @@ -592,11 +590,11 @@ public class FindUtil { return result; } - private static class MyListener extends FocusAdapter implements CaretListener { + private static class MyListener implements CaretListener { private final Editor myEditor; private final RangeHighlighter mySegmentHighlighter; - private MyListener(Editor editor, RangeHighlighter segmentHighlighter) { + private MyListener(@NotNull Editor editor, @NotNull RangeHighlighter segmentHighlighter) { myEditor = editor; mySegmentHighlighter = segmentHighlighter; } @@ -606,27 +604,20 @@ public class FindUtil { } private void removeAll() { - myEditor.getMarkupModel().removeHighlighter(mySegmentHighlighter); - myEditor.getContentComponent().addFocusListener(this); myEditor.getCaretModel().removeCaretListener(this); + myEditor.getMarkupModel().removeHighlighter(mySegmentHighlighter); } } private static void processNotFound(final Editor editor, String stringToFind, FindModel model, Project project) { - String message = FindBundle.message("find.search.string.not.found.message", stringToFind); if (model.isGlobal()) { final FindModel newModel = (FindModel)model.clone(); FindManager findManager = FindManager.getInstance(project); Document document = editor.getDocument(); - FindResult result; - if (newModel.isForward()) { - result = findManager.findString(document.getCharsSequence(), 0, model, getVirtualFile(editor)); - } - else { - result = findManager.findString(document.getCharsSequence(), document.getTextLength(), model, getVirtualFile(editor)); - } + FindResult result = findManager.findString(document.getCharsSequence(), + newModel.isForward() ? 0 : document.getTextLength(), model, getVirtualFile(editor)); if (!result.isStringFound()) { result = null; } diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java index b893b4b677b8..e38b1eec2dca 100644 --- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java @@ -47,12 +47,14 @@ import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.PopupStep; import com.intellij.openapi.ui.popup.util.BaseListPopupStep; import com.intellij.openapi.util.*; +import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusListener; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFocusManager; +import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.WindowManager; import com.intellij.pom.Navigatable; @@ -78,6 +80,8 @@ import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.*; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.Set; @@ -114,13 +118,68 @@ public class NavBarPanel extends OpaquePanel.List implements DataProvider, Popup private AtomicBoolean myModelUpdating = new AtomicBoolean(Boolean.FALSE); private MyItemLabel myContextObject; + private PropertyChangeListener myFocusListener = new PropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent evt) { + if ("focusOwner".equals(evt.getPropertyName()) || "permanentFocusOwner".equals(evt.getPropertyName())) { + myFocusChangedAlarm.cancelAllRequests(); + myFocusChangedAlarm.addRequest(myFocusChangedRunnable, 250); + } + } + }; + + private Alarm myFocusChangedAlarm = new Alarm(); + private Runnable myFocusChangedRunnable = new Runnable() { + @Override + public void run() { + processFocusChanged(); + } + }; + + private void processFocusChanged() { + if (!isShowing()) { + return; + } + + IdeFocusManager.getInstance(myProject).doWhenFocusSettlesDown(new Runnable() { + @Override + public void run() { + Window wnd = SwingUtilities.windowForComponent(NavBarPanel.this); + if (wnd == null) return; + + Component focus = null; + + if (!wnd.isActive()) { + IdeFrame frame = UIUtil.getParentOfType(IdeFrame.class, NavBarPanel.this); + if (frame != null) { + focus = IdeFocusManager.getInstance(myProject).getLastFocusedFor(frame); + } + } else { + final Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); + if (window instanceof Dialog) { + final Dialog dialog = (Dialog)window; + if (dialog.isModal() && !SwingUtilities.isDescendingFrom(NavBarPanel.this, dialog)) { + return; + } + } + } + + if (focus != null && focus.isShowing()) { + queueModelUpdate(DataManager.getInstance().getDataContext(focus)); + } else if (wnd.isActive()) { + queueModelUpdateFromFocus(); + } + } + }); + } + public NavBarPanel(final Project project) { super(new FlowLayout(FlowLayout.LEFT, 5, 0), UIUtil.isUnderGTKLookAndFeel() ? Color.WHITE : UIUtil.getListBackground()); myProject = project; myModel = new NavBarModel(myProject); - myUpdateQueue = new MergingUpdateQueue("NavBar", 150, true, MergingUpdateQueue.ANY_COMPONENT, project, null); + myUpdateQueue = new MergingUpdateQueue("NavBar", Registry.intValue("navbar.updateMergeTime"), true, MergingUpdateQueue.ANY_COMPONENT, project, null); PopupHandler.installPopupHandler(this, IdeActions.GROUP_PROJECT_VIEW_POPUP, ActionPlaces.NAVIGATION_BAR); @@ -445,6 +504,17 @@ public class NavBarPanel extends OpaquePanel.List implements DataProvider, Popup if (eachLabel.getObject() == null || !eachLabel.getObject().equals(eachElement)) { return true; } + + + SimpleTextAttributes modelAttributes1 = myModel.getTextAttributes(eachElement, true); + SimpleTextAttributes modelAttributes2 = myModel.getTextAttributes(eachElement, false); + SimpleTextAttributes labelAttributes = eachLabel.getAttributes(); + + if (!modelAttributes1.toTextAttributes().equals(labelAttributes.toTextAttributes()) + && !modelAttributes2.toTextAttributes().equals(labelAttributes.toTextAttributes())) { + return true; + } + index++; } @@ -895,15 +965,14 @@ public class NavBarPanel extends OpaquePanel.List implements DataProvider, Popup final MyPsiTreeChangeAdapter psiListener = new MyPsiTreeChangeAdapter(); final MyProblemListener problemListener = new MyProblemListener(); final MyFileStatusListener fileStatusListener = new MyFileStatusListener(); - final MyTimerListener timerListener = new MyTimerListener(); PsiManager.getInstance(myProject).addPsiTreeChangeListener(psiListener); WolfTheProblemSolver.getInstance(myProject).addProblemListener(problemListener); FileStatusManager.getInstance(myProject).addFileStatusListener(fileStatusListener); - final ActionManagerEx actionManager = ActionManagerEx.getInstanceEx(); - actionManager.addTimerListener(10000, timerListener); + + KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(myFocusListener); final MessageBusConnection busConnection = myProject.getMessageBus().connect(); busConnection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyModuleRootListener()); @@ -923,7 +992,6 @@ public class NavBarPanel extends OpaquePanel.List implements DataProvider, Popup myDetacher = new Runnable() { public void run() { - ActionManagerEx.getInstanceEx().removeTimerListener(timerListener); busConnection.disconnect(); WolfTheProblemSolver.getInstance(myProject).removeProblemListener(problemListener); @@ -934,6 +1002,7 @@ public class NavBarPanel extends OpaquePanel.List implements DataProvider, Popup } public void uninstallListeners() { + KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener(myFocusListener); myDetacher.run(); myDetacher = null; } @@ -1131,6 +1200,10 @@ public class NavBarPanel extends OpaquePanel.List implements DataProvider, Popup return myObject; } + public SimpleTextAttributes getAttributes() { + return myAttributes; + } + private void update() { clear(); @@ -1160,37 +1233,6 @@ public class NavBarPanel extends OpaquePanel.List implements DataProvider, Popup } } - private final class MyTimerListener implements TimerListener { - - public ModalityState getModalityState() { - return ModalityState.stateForComponent(NavBarPanel.this); - } - - public void run() { - if (!isShowing()) { - return; - } - - IdeFocusManager.getInstance(myProject).doWhenFocusSettlesDown(new Runnable() { - @Override - public void run() { - Window wnd = SwingUtilities.windowForComponent(NavBarPanel.this); - if (wnd == null || !wnd.isActive()) return; - - final Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); - if (window instanceof Dialog) { - final Dialog dialog = (Dialog)window; - if (dialog.isModal() && !SwingUtilities.isDescendingFrom(NavBarPanel.this, dialog)) { - return; - } - } - - queueModelUpdateFromFocus(); - } - }); - } - } - private final class MyIdeView implements IdeView { public void selectElement(PsiElement element) { diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/actions/ProjectViewActionGroup.java b/platform/lang-impl/src/com/intellij/ide/projectView/actions/ProjectViewActionGroup.java deleted file mode 100644 index f34fcf03bcbb..000000000000 --- a/platform/lang-impl/src/com/intellij/ide/projectView/actions/ProjectViewActionGroup.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.intellij.ide.projectView.actions; - -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.DefaultActionGroup; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.actionSystem.Presentation; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.wm.ToolWindowId; -import com.intellij.openapi.wm.ToolWindowManager; - -public final class ProjectViewActionGroup extends DefaultActionGroup { - public ProjectViewActionGroup() { - super(); - } - - public void update(AnActionEvent event){ - Presentation presentation = event.getPresentation(); - Project project = PlatformDataKeys.PROJECT.getData(event.getDataContext()); - if (project == null) { - presentation.setVisible(false); - return; - } - String id = ToolWindowManager.getInstance(project).getActiveToolWindowId(); - boolean isProjectViewActive = ToolWindowId.PROJECT_VIEW.equals(id); - presentation.setVisible(isProjectViewActive); - } -} \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewDropTarget.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewDropTarget.java index 8f46b899e898..b5b451796619 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewDropTarget.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewDropTarget.java @@ -255,11 +255,6 @@ class ProjectViewDropTarget implements DnDNativeTarget { } } - protected boolean fromSameProject(final PsiElement[] sourceElements, final PsiElement targetElement) { - return targetElement != null && sourceElements.length > 0 && sourceElements[0] != null && - targetElement.getProject() == sourceElements[0].getProject(); - } - } protected PsiFileSystemItem[] getPsiFiles(List fileList) { @@ -292,7 +287,7 @@ class ProjectViewDropTarget implements DnDNativeTarget { final PsiElement targetElement = getPsiElement(targetNode); return sourceElements.length == 0 || ((targetNode == null || targetElement != null) && - fromSameProject(sourceElements, targetElement) && MoveHandler.canMove(sourceElements, targetElement)); + MoveHandler.canMove(sourceElements, targetElement)); } public void doDrop(@NotNull final TreeNode[] sourceNodes, @NotNull final TreeNode targetNode) { @@ -348,7 +343,7 @@ class ProjectViewDropTarget implements DnDNativeTarget { final PsiElement[] sourceElements = getPsiElements(sourceNodes); final PsiElement targetElement = getPsiElement(targetNode); return (targetElement instanceof PsiDirectoryContainer || targetElement instanceof PsiDirectory) && - fromSameProject(sourceElements, targetElement) && CopyHandler.canCopy(sourceElements); + CopyHandler.canCopy(sourceElements); } public void doDrop(@NotNull final TreeNode[] sourceNodes, @NotNull final TreeNode targetNode) { diff --git a/platform/lang-impl/src/com/intellij/ide/scriptingContext/ScriptingLibraryMappings.java b/platform/lang-impl/src/com/intellij/ide/scriptingContext/ScriptingLibraryMappings.java index c796667b7a03..93286a418bc8 100644 --- a/platform/lang-impl/src/com/intellij/ide/scriptingContext/ScriptingLibraryMappings.java +++ b/platform/lang-impl/src/com/intellij/ide/scriptingContext/ScriptingLibraryMappings.java @@ -91,18 +91,27 @@ public class ScriptingLibraryMappings extends LanguagePerFileMappings - + @@ -80,7 +80,7 @@ - + diff --git a/platform/lang-impl/src/com/intellij/ide/scriptingContext/ui/EditLibraryDialog.java b/platform/lang-impl/src/com/intellij/ide/scriptingContext/ui/EditLibraryDialog.java index 09d095f8b5cd..182a0561cc31 100644 --- a/platform/lang-impl/src/com/intellij/ide/scriptingContext/ui/EditLibraryDialog.java +++ b/platform/lang-impl/src/com/intellij/ide/scriptingContext/ui/EditLibraryDialog.java @@ -15,6 +15,7 @@ */ package com.intellij.ide.scriptingContext.ui; +import com.intellij.ide.IdeBundle; import com.intellij.ide.scriptingContext.LangScriptingContextProvider; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; @@ -170,7 +171,7 @@ public class EditLibraryDialog extends DialogWrapper { private class LibFileChooserDescriptor extends FileChooserDescriptor { public LibFileChooserDescriptor() { super (true, true, false, true, false, false); - setTitle("Select library file or directory"); //TODO Move to resources + setTitle(IdeBundle.message("scripting.lib.select.root")); } @Override @@ -192,9 +193,9 @@ public class EditLibraryDialog extends DialogWrapper { public String getColumnName(int column) { switch(column) { case FILE_LOCATION_COL: - return "Location"; //TODO Move to resources - case FILE_TYPE_COL: //TODO Move to resources - return "Type"; + return IdeBundle.message("scripting.lib.file.location"); + case FILE_TYPE_COL: + return IdeBundle.message("scripting.lib.file.type"); } return ""; } @@ -314,7 +315,7 @@ public class EditLibraryDialog extends DialogWrapper { @Override protected void doOKAction() { if (!isLibNameValid(myLibName.getText())) { - Messages.showErrorDialog(myProject, "Invalid library name", "Error"); //TODO Move to resources + Messages.showErrorDialog(myProject, IdeBundle.message("scripting.lib.invalid.name"), "Error"); return; } super.doOKAction(); diff --git a/platform/lang-impl/src/com/intellij/ide/scriptingContext/ui/ScriptingContextsConfigurable.java b/platform/lang-impl/src/com/intellij/ide/scriptingContext/ui/ScriptingContextsConfigurable.java index 44da63392e45..1568aad46ea5 100644 --- a/platform/lang-impl/src/com/intellij/ide/scriptingContext/ui/ScriptingContextsConfigurable.java +++ b/platform/lang-impl/src/com/intellij/ide/scriptingContext/ui/ScriptingContextsConfigurable.java @@ -15,6 +15,7 @@ */ package com.intellij.ide.scriptingContext.ui; +import com.intellij.ide.IdeBundle; import com.intellij.ide.scriptingContext.ScriptingLibraryMappings; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.libraries.scripting.ScriptingLibraryTable; @@ -34,8 +35,10 @@ public class ScriptingContextsConfigurable extends LanguagePerFileConfigurable - + @@ -42,7 +42,7 @@ - + @@ -50,7 +50,7 @@ - + diff --git a/platform/lang-impl/src/com/intellij/ide/scriptingContext/ui/ScriptingLibraryIcons.java b/platform/lang-impl/src/com/intellij/ide/scriptingContext/ui/ScriptingLibraryIcons.java new file mode 100644 index 000000000000..b041de960f32 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/ide/scriptingContext/ui/ScriptingLibraryIcons.java @@ -0,0 +1,29 @@ +/* + * 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.ide.scriptingContext.ui; + +import com.intellij.openapi.util.IconLoader; + +import javax.swing.*; + +/** + * @author Rustam Vishnyakov + */ +public abstract class ScriptingLibraryIcons { + public static final Icon CHECKED_ICON = IconLoader.getIcon("/actions/check_16.png"); + public static final Icon UNCHECKED_ICON = null; + public static final Icon CLEAR_ICON = IconLoader.getIcon("/general/reset.png"); +} diff --git a/platform/lang-impl/src/com/intellij/injected/editor/CaretModelWindow.java b/platform/lang-impl/src/com/intellij/injected/editor/CaretModelWindow.java index 0ca9958af275..9c227b364a81 100644 --- a/platform/lang-impl/src/com/intellij/injected/editor/CaretModelWindow.java +++ b/platform/lang-impl/src/com/intellij/injected/editor/CaretModelWindow.java @@ -23,6 +23,7 @@ import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.editor.event.CaretEvent; import com.intellij.openapi.editor.event.CaretListener; import com.intellij.openapi.editor.ex.EditorEx; +import org.jetbrains.annotations.NotNull; /** * @author Alexey @@ -46,12 +47,12 @@ public class CaretModelWindow implements CaretModel { myDelegate.moveCaretRelatively(columnShift, lineShift, withSelection, blockSelection, scrollToCaret); } - public void moveToLogicalPosition(final LogicalPosition pos) { + public void moveToLogicalPosition(@NotNull final LogicalPosition pos) { LogicalPosition hostPos = myEditorWindow.injectedToHost(pos); myDelegate.moveToLogicalPosition(hostPos); } - public void moveToVisualPosition(final VisualPosition pos) { + public void moveToVisualPosition(@NotNull final VisualPosition pos) { LogicalPosition hostPos = myEditorWindow.injectedToHost(myEditorWindow.visualToLogicalPosition(pos)); myDelegate.moveToLogicalPosition(hostPos); } @@ -66,10 +67,12 @@ public class CaretModelWindow implements CaretModel { myDelegate.moveToOffset(hostOffset, locateBeforeSoftWrap); } + @NotNull public LogicalPosition getLogicalPosition() { return myEditorWindow.hostToInjected(myHostEditor.offsetToLogicalPosition(myDelegate.getOffset())); } + @NotNull public VisualPosition getVisualPosition() { LogicalPosition logicalPosition = getLogicalPosition(); return myEditorWindow.logicalToVisualPosition(logicalPosition); @@ -80,7 +83,7 @@ public class CaretModelWindow implements CaretModel { } private final ListenerWrapperMap myCaretListeners = new ListenerWrapperMap(); - public void addCaretListener(final CaretListener listener) { + public void addCaretListener(@NotNull final CaretListener listener) { CaretListener wrapper = new CaretListener() { public void caretPositionChanged(CaretEvent e) { CaretEvent event = new CaretEvent(myEditorWindow, myEditorWindow.hostToInjected(e.getOldPosition()), @@ -92,7 +95,7 @@ public class CaretModelWindow implements CaretModel { myDelegate.addCaretListener(wrapper); } - public void removeCaretListener(final CaretListener listener) { + public void removeCaretListener(@NotNull final CaretListener listener) { CaretListener wrapper = myCaretListeners.removeWrapper(listener); if (wrapper != null) { myDelegate.removeCaretListener(wrapper); diff --git a/platform/lang-impl/src/com/intellij/injected/editor/DocumentWindowImpl.java b/platform/lang-impl/src/com/intellij/injected/editor/DocumentWindowImpl.java index 9fb87784388c..0ba92d9eaff1 100644 --- a/platform/lang-impl/src/com/intellij/injected/editor/DocumentWindowImpl.java +++ b/platform/lang-impl/src/com/intellij/injected/editor/DocumentWindowImpl.java @@ -68,19 +68,20 @@ public class DocumentWindowImpl extends UserDataHolderBase implements Disposable private static class CachedText { private final String text; - private final long modstamp; + private final long modificationStamp; - private CachedText(String text, long modstamp) { + private CachedText(@NotNull String text, long modificationStamp) { this.text = text; - this.modstamp = modstamp; + this.modificationStamp = modificationStamp; } - public String getText() { + @NotNull + private String getText() { return text; } - public long getModstamp() { - return modstamp; + private long getModificationStamp() { + return modificationStamp; } } @@ -146,17 +147,16 @@ public class DocumentWindowImpl extends UserDataHolderBase implements Disposable } public String getText() { - if (myCachedText != null && myCachedText.getModstamp() != myDelegate.getModificationStamp()) { - myCachedText = null; + CachedText cachedText = myCachedText; + + if (cachedText == null || cachedText.getModificationStamp() != getModificationStamp()) { + myCachedText = cachedText = new CachedText(calcText(), getModificationStamp()); } - if (myCachedText == null) { - myCachedText = new CachedText(calcText(), myDelegate.getModificationStamp()); - } - - return myCachedText.getText(); + return cachedText.getText(); } + @NotNull private String calcText() { StringBuilder text = new StringBuilder(); CharSequence hostText = myDelegate.getCharsSequence(); diff --git a/platform/lang-impl/src/com/intellij/injected/editor/MarkupModelWindow.java b/platform/lang-impl/src/com/intellij/injected/editor/MarkupModelWindow.java index af796c6a3ee9..e681c577d784 100644 --- a/platform/lang-impl/src/com/intellij/injected/editor/MarkupModelWindow.java +++ b/platform/lang-impl/src/com/intellij/injected/editor/MarkupModelWindow.java @@ -65,7 +65,7 @@ class MarkupModelWindow extends UserDataHolderBase implements MarkupModelEx { int endOffset, int layer, TextAttributes textAttributes, - HighlighterTargetArea targetArea, + @NotNull HighlighterTargetArea targetArea, boolean isPersistent, Consumer changeAttributesAction) { TextRange hostRange = myDocument.injectedToHost(new ProperTextRange(startOffset, endOffset)); @@ -85,7 +85,7 @@ class MarkupModelWindow extends UserDataHolderBase implements MarkupModelEx { return myHostModel.addLineHighlighter(hostLine, layer, textAttributes); } - public void removeHighlighter(final RangeHighlighter rangeHighlighter) { + public void removeHighlighter(@NotNull final RangeHighlighter rangeHighlighter) { myHostModel.removeHighlighter(rangeHighlighter); } diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/ex/util/LayeredLexerEditorHighlighter.java b/platform/lang-impl/src/com/intellij/openapi/editor/ex/util/LayeredLexerEditorHighlighter.java index 88cbc3339233..15897a46b278 100644 --- a/platform/lang-impl/src/com/intellij/openapi/editor/ex/util/LayeredLexerEditorHighlighter.java +++ b/platform/lang-impl/src/com/intellij/openapi/editor/ex/util/LayeredLexerEditorHighlighter.java @@ -350,13 +350,13 @@ public class LayeredLexerEditorHighlighter extends LexerEditorHighlighter { final int newEnd = start + tokenText.length(); if (oldMapping.range.getStartOffset() != start || - oldMapping.range.getEndOffset() != newEnd - ) { + oldMapping.range.getEndOffset() != newEnd) { + oldMapping.range.dispose(); oldMapping.range = doc.createRangeMarker(start, newEnd); } } - public MappedRange insertMapping(int tokenIndex, IElementType outerToken) { + private MappedRange insertMapping(int tokenIndex, IElementType outerToken) { CharSequence tokenText = getTokenText(tokenIndex); final int length = tokenText.length(); @@ -367,7 +367,8 @@ public class LayeredLexerEditorHighlighter extends LexerEditorHighlighter { doc.insertString(insertOffset, new MergingCharSequence(mySeparator, tokenText)); insertOffset += mySeparator.length(); - return new MappedRange(this, doc.createRangeMarker(insertOffset, insertOffset + length), outerToken); + RangeMarker marker = doc.createRangeMarker(insertOffset, insertOffset + length); + return new MappedRange(this, marker, outerToken); } private CharSequence getTokenText(final int tokenIndex) { @@ -386,12 +387,13 @@ public class LayeredLexerEditorHighlighter extends LexerEditorHighlighter { return null; } - public void removeMapping(MappedRange mapping) { + private void removeMapping(MappedRange mapping) { RangeMarker rangeMarker = mapping.range; if (rangeMarker.isValid()) { final int start = rangeMarker.getStartOffset(); final int end = rangeMarker.getEndOffset(); doc.deleteString(start - mySeparator.length(), end); + rangeMarker.dispose(); } } } diff --git a/platform/lang-impl/src/com/intellij/psi/PsiAnchor.java b/platform/lang-impl/src/com/intellij/psi/PsiAnchor.java index 1fb72c4108dc..19e00da24583 100644 --- a/platform/lang-impl/src/com/intellij/psi/PsiAnchor.java +++ b/platform/lang-impl/src/com/intellij/psi/PsiAnchor.java @@ -27,6 +27,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.impl.light.LightElement; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.PsiFileWithStubSupport; +import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubBase; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubTree; @@ -35,6 +36,7 @@ import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.List; import java.util.Set; /** @@ -64,7 +66,7 @@ public abstract class PsiAnchor { final StubBasedPsiElement elt = (StubBasedPsiElement)element; if (elt.getStub() != null || elt.getElementType().shouldCreateStub(element.getNode())) { int index = calcStubIndex((StubBasedPsiElement)element); - if (index != -1) return new StubIndexReference(file, index); + if (index != -1) return new StubIndexReference(file, index, elt.getElementType()); } } @@ -219,8 +221,10 @@ public abstract class PsiAnchor { private final VirtualFile myVirtualFile; private final Project myProject; private final int myIndex; + private final IStubElementType myElementType; - public StubIndexReference(@NotNull PsiFile file, final int index) { + public StubIndexReference(@NotNull PsiFile file, final int index, IStubElementType elementType) { + myElementType = elementType; myVirtualFile = file.getVirtualFile(); myProject = file.getProject(); myIndex = index; @@ -248,7 +252,11 @@ public abstract class PsiAnchor { } } - StubElement stub = tree.getPlainList().get(myIndex); + List> list = tree.getPlainList(); + if (myIndex >= list.size()) return null; + StubElement stub = list.get(myIndex); + + if (stub.getStubType() != myElementType) return null; if (foreign) { final PsiElement cachedPsi = ((StubBase)stub).getCachedPsi(); @@ -271,12 +279,12 @@ public abstract class PsiAnchor { final StubIndexReference that = (StubIndexReference)o; - return myIndex == that.myIndex && myVirtualFile.equals(that.myVirtualFile); + return myIndex == that.myIndex && myVirtualFile.equals(that.myVirtualFile) && myElementType.equals(that.myElementType); } @Override public int hashCode() { - return 31 * myVirtualFile.hashCode() + myIndex; + return (31 * myVirtualFile.hashCode() + myIndex) * 31 + myElementType.hashCode(); } public int getStartOffset() { diff --git a/platform/lang-impl/src/com/intellij/psi/SingleRootFileViewProvider.java b/platform/lang-impl/src/com/intellij/psi/SingleRootFileViewProvider.java index 6a43ad6d5989..89a00b045a08 100644 --- a/platform/lang-impl/src/com/intellij/psi/SingleRootFileViewProvider.java +++ b/platform/lang-impl/src/com/intellij/psi/SingleRootFileViewProvider.java @@ -257,6 +257,11 @@ public class SingleRootFileViewProvider extends UserDataHolderBase implements Fi return fileSizeIsGreaterThan(vFile, PersistentFS.MAX_INTELLISENSE_FILESIZE); } + public static boolean isTooLarge(final VirtualFile vFile, final long contentSize) { + if (Boolean.TRUE.equals(vFile.getUserData(ourNoSizeLimitKey))) return false; + return contentSize > PersistentFS.MAX_INTELLISENSE_FILESIZE; + } + private static boolean fileSizeIsGreaterThan(final VirtualFile vFile, final long maxInBytes) { if (vFile instanceof LightVirtualFile) { // This is optimization in order to avoid conversion of [large] file contents to bytes diff --git a/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java b/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java index a99d6c01788c..59754f994cb8 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/SharedPsiElementImplUtil.java @@ -68,7 +68,7 @@ public class SharedPsiElementImplUtil { LOG.error(element); } for (TextRange range : ReferenceRange.getRanges(reference)) { - if (range.getStartOffset() <= offset && offset <= range.getEndOffset()) { + if (range.containsOffset(offset)) { outReferences.add(reference); } } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java index ed82047b391b..7dcd48d7a11d 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java @@ -652,7 +652,7 @@ public class FileManagerImpl implements FileManager { if (!vFile.isDirectory()) { PsiFile psiFile = findFile(vFile); - if (psiFile != null) { + if (psiFile != null && psiFile.getProject() == myManager.getProject()) { PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager); treeEvent.setParent(parentDir); myManager.beforeChildAddition(treeEvent); @@ -662,7 +662,7 @@ public class FileManagerImpl implements FileManager { } else { PsiDirectory psiDir = findDirectory(vFile); - if (psiDir != null) { + if (psiDir != null && psiDir.getProject() == myManager.getProject()) { PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager); treeEvent.setParent(parentDir); myManager.beforeChildAddition(treeEvent); diff --git a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/FileElementInfo.java b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/FileElementInfo.java index 0047cd5683da..c825b9ec7302 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/FileElementInfo.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/FileElementInfo.java @@ -18,10 +18,8 @@ package com.intellij.psi.impl.smartPointers; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiManager; import org.jetbrains.annotations.NotNull; /** @@ -50,4 +48,8 @@ class FileElementInfo implements SmartPointerElementInfo { myFile = SelfElementInfo.restoreFile(myFile, myProject); return myFile; } + + @Override + public void dispose() { + } } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/LazyPointerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/LazyPointerImpl.java index 95f0c04401b8..b091bc7de1b2 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/LazyPointerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/LazyPointerImpl.java @@ -110,4 +110,8 @@ public class LazyPointerImpl implements SmartPointerEx return null; } + @Override + public void dispose() { + if (myPointer != null) ((SmartPointerEx)myPointer).dispose(); + } } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java index 03cb478976a2..8f338691024f 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SelfElementInfo.java @@ -113,6 +113,13 @@ class SelfElementInfo implements SmartPointerElementInfo { return null; } + @Override + public void dispose() { + if (myMarker != null) { + myMarker.dispose(); + } + } + @Nullable public static PsiFile restoreFile(PsiFile file,@NotNull Project project) { if (file == null) return null; diff --git a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerElementInfo.java b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerElementInfo.java index 9c85e8082473..98435ed3f3ca 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerElementInfo.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerElementInfo.java @@ -28,4 +28,6 @@ interface SmartPointerElementInfo { @Nullable PsiElement restoreElement(); + + void dispose(); } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerEx.java b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerEx.java index 8133f292798a..4ab980b7ef08 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerEx.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerEx.java @@ -21,4 +21,5 @@ import com.intellij.psi.SmartPsiElementPointer; public interface SmartPointerEx extends SmartPsiElementPointer { void fastenBelt(); void documentAndPsiInSync(); + void dispose(); } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPsiElementPointerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPsiElementPointerImpl.java index 507b4fe0856f..da8b80f07d38 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPsiElementPointerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/smartPointers/SmartPsiElementPointerImpl.java @@ -149,6 +149,15 @@ class SmartPsiElementPointerImpl implements SmartPointerEx } } + @Override + public void dispose() { + if (myElementInfo != null) { + myElementInfo.dispose(); + myElementInfo = null; + myElement = null; + } + } + public void fastenBelt() { if (myElementInfo != null && myElement != null && myElement.isValid()) return; @@ -156,5 +165,4 @@ class SmartPsiElementPointerImpl implements SmartPointerEx myElementInfo = createElementInfo(); } } - } diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java index c139c4157a18..3f41043d0915 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java @@ -26,6 +26,7 @@ import com.intellij.lang.Language; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; +import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.colors.TextAttributesKey; @@ -57,6 +58,7 @@ import com.intellij.reference.SoftReference; import com.intellij.util.IncorrectOperationException; import com.intellij.util.PatchedSoftReference; import com.intellij.util.PatchedWeakReference; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; @@ -242,6 +244,7 @@ public abstract class PsiFileImpl extends ElementBase implements PsiFileEx, PsiF return findTreeForStub(ast, stubs, stub); } + @Nullable private static ASTNode findTreeForStub(ASTNode tree, final Iterator> stubs, final StubElement stub) { final IElementType type = tree.getElementType(); @@ -258,46 +261,39 @@ public abstract class PsiFileImpl extends ElementBase implements PsiFileEx, PsiF return null; } - - private void switchFromStubToAST(ASTNode root, final Iterator> stubs) { + private void switchFromStubToAST(final ASTNode root, final Iterator> stubs) { final IElementType contentElementType = getContentElementType(); if (!(contentElementType instanceof IStubFileElementType)) { - throw new AssertionError("Invalid content element type: " + contentElementType + "; elementType=" + myElementType + "; file=" + getClass() + "; viewProvider=" + getViewProvider()); + throw new AssertionError("A stub in a non-stub file, stubs=" + ContainerUtil.collect(stubs)); } - ((TreeElement)root).acceptTree(new RecursiveTreeElementWalkingVisitor() { - final StubBuilder builder = ((IStubFileElementType)contentElementType).getBuilder(); + final StubBuilder builder = ((IStubFileElementType)contentElementType).getBuilder(); + ((TreeElement)root).acceptTree(new RecursiveTreeElementWalkingVisitor() { @Override protected void visitNode(TreeElement tree) { final IElementType type = tree.getElementType(); - CompositeElement treeParent = tree.getTreeParent(); - if(treeParent != null && - builder.skipChildProcessingWhenBuildingStubs(treeParent.getElementType(), type)) { + final CompositeElement treeParent = tree.getTreeParent(); + if (treeParent != null && builder.skipChildProcessingWhenBuildingStubs(treeParent.getElementType(), type)) { return; } if (type instanceof IStubElementType && ((IStubElementType)type).shouldCreateStub(tree)) { if (!stubs.hasNext()) { - LOG.error("Stub list in" + - this + - " " + - getName() + - " has fewer elements than PSI. Last AST element: " + - tree.getElementType() + - " " + - tree); + rebuildStub(); + LOG.error("Stub list in " + getName() + " has fewer elements than PSI. Last AST element: " + + tree.getElementType() + " " + tree); + stopWalking(); + return; } + final StubElement stub = stubs.next(); if (stub.getStubType() != tree.getElementType()) { rebuildStub(); - LOG.error("Stub and PSI element type mismatch in " + - getName() + - ": stub " + - stub + - ", AST " + - tree.getElementType() + - "; " + - tree); + LOG.error("Stub and PSI element type mismatch in " + getName() + ": stub " + stub + ", AST " + + tree.getElementType() + "; " + tree); + stopWalking(); + return; } + final PsiElement psi = stub.getPsi(); ((CompositeElement)tree).setPsi(psi); final StubBasedPsiElementBase base = (StubBasedPsiElementBase)psi; @@ -893,22 +889,40 @@ public abstract class PsiFileImpl extends ElementBase implements PsiFileEx, PsiF final PsiFileImpl file = this; final Iterator> stubs = stubTree.getPlainList().iterator(); - stubs.next(); // skip file root stub + final StubElement rootStub = stubs.next(); // skip file root stub final FileElement fileRoot = file.getTreeElement(); assert fileRoot != null; - bindStubs(fileRoot, stubs, ((IStubFileElementType)getContentElementType()).getBuilder()); + try { + bindStubs(fileRoot, stubs, ((IStubFileElementType)getContentElementType()).getBuilder()); + } + catch (BindingFailedException e) { + String message = e.getMessage(); + if (((ApplicationEx)ApplicationManager.getApplication()).isInternal()) { + message = new StringBuilder(message) + .append("\n=== AST ===\n").append(DebugUtil.treeToString(fileRoot, true)) + .append("=== stub tree ===\n").append(DebugUtil.stubTreeToString(rootStub)) + .append("=== text===\n").append(getText()) + .append("\n======").toString(); + } + assert false : message; + } } - @Nullable - private StubElement bindStubs(final ASTNode tree, final Iterator> stubs, final StubBuilder builder) { + private static class BindingFailedException extends RuntimeException { + private BindingFailedException(final String message) { + super(message); + } + } + + private void bindStubs(final ASTNode tree, final Iterator> stubs, final StubBuilder builder) { final IElementType type = tree.getElementType(); if (type instanceof IStubElementType && ((IStubElementType) type).shouldCreateStub(tree)) { final StubElement stub = stubs.next(); if (stub.getStubType() != tree.getElementType()) { rebuildStub(); - assert false : "Stub and PSI element type mismatch in " + getName() + ": stub:" + stub + ", AST:" + tree.getElementType(); + throw new BindingFailedException("Stub and PSI element type mismatch in " + getName() + ": stub:" + stub + ", AST:" + tree.getElementType()); } //noinspection unchecked @@ -917,14 +931,9 @@ public abstract class PsiFileImpl extends ElementBase implements PsiFileEx, PsiF for (ASTNode node : tree.getChildren(null)) { if (!builder.skipChildProcessingWhenBuildingStubs(type, node.getElementType())) { - final StubElement res = bindStubs(node, stubs, builder); - if (res != null) { - return res; - } + bindStubs(node, stubs, builder); } } - - return null; } private void rebuildStub() { diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java index dcdc78135e83..83491d3a0715 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java @@ -24,10 +24,7 @@ import com.intellij.injected.editor.DocumentWindow; import com.intellij.lang.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.editor.CaretModel; -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.VisualPosition; +import com.intellij.openapi.editor.*; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; @@ -394,9 +391,99 @@ public class CodeStyleManagerImpl extends CodeStyleManager { } return false; } + + private static boolean isWhiteSpaceSymbol(char c) { + return c == ' ' || c == '\t' || c == '\n'; + } + + /** + * Formatter trims line that contains white spaces symbols only, however, there is a possible case that we want + * to preserve them for particular line (e.g. for live template that defines blank line that contains $END$ marker). + *

+ * Current approach is to do the following: + *

+   * 
    + *
  1. Insert dummy text at the end of the blank line which white space symbols should be preserved;
  2. + *
  3. Perform formatting;
  4. + *
  5. Remove dummy text;
  6. + *
+ *
+ *

+ * This method inserts that dummy text if necessary (if target line contains white space symbols only). + *

+ * Please note that it tries to do that via PSI at first (checks if given offset points to + * {@link TokenType#WHITE_SPACE white space element} and inserts dummy text as dedicated element if necessary) and, + * in case of the negative answer, tries to perform the examination considering document just as a sequence of characters + * and assuming that white space symbols are white spaces, tabulations and line feeds. The rationale for such an approach is: + *

+   * 
    + *
  • + * there is a possible case that target language considers symbols over than white spaces, tabulations and line feeds + * to be white spaces and the answer lays at PSI structure of the file; + *
  • + *
  • + * dummy text inserted during PSI-based processing has {@link TokenType#NEW_LINE_INDENT special type} that may be treated + * specifically during formatting; + *
  • + *
+ *
+ *

+ * Note: it's expected that the whole white space region that contains given offset is processed in a way that all + * {@link RangeMarker range markers} registered for the given offset are expanded to the whole white space region. + * E.g. there is a possible case that particular range marker serves for defining formatting range, hence, its start/end offsets + * are updated correspondingly after current method call and whole white space region is reformatted. + * + * @param document target document + * @param offset offset that defines end boundary of the target line text fragment (start boundary is the first line's symbol) + * @return text range that points to the newly inserted dummy text if any; null otherwise + */ + @Nullable + public static TextRange insertNewLineIndentMarker(@NotNull PsiFile file, @NotNull Document document, int offset) + throws IncorrectOperationException + { + TextRange result = insertNewLineIndentMarker(file, offset); + if (result == null) { + result = insertNewLineIndentMarker(document, offset); + } + return result; + } + + + @Nullable + private static TextRange insertNewLineIndentMarker(@NotNull Document document, final int offset) { + CharSequence text = document.getCharsSequence(); + if (offset < 0 || offset >= text.length() || !isWhiteSpaceSymbol(text.charAt(offset))) { + return null; + } + + int start = offset; + for (int i = offset - 1; i >= 0; i--) { + if (!isWhiteSpaceSymbol(text.charAt(i))) { + break; + } + start = i; + } + + int end = offset; + for (; end < text.length(); end++) { + if (!isWhiteSpaceSymbol(text.charAt(end))) { + break; + } + } + + StringBuilder buffer = new StringBuilder(); + buffer.append(text.subSequence(start, end)); + + // Modify the document in order to expand range markers pointing to the given offset to the whole white space range. + document.deleteString(start, end); + document.insertString(start, buffer); + + document.insertString(offset, DUMMY_IDENTIFIER); + return new TextRange(offset, offset + DUMMY_IDENTIFIER.length()); + } @Nullable - public static PsiElement insertNewLineIndentMarker(@NotNull PsiFile file, int offset) throws IncorrectOperationException { + private static TextRange insertNewLineIndentMarker(@NotNull PsiFile file, int offset) throws IncorrectOperationException { CheckUtil.checkWritable(file); final CharTable charTable = ((FileElement)SourceTreeToPsiMap.psiElementToTree(file)).getCharTable(); PsiElement elementAt = findElementInTreeWithFormatterEnabled(file, offset); @@ -420,7 +507,8 @@ public class CodeStyleManagerImpl extends CodeStyleManager { ASTNode space1 = splitSpaceElement((TreeElement)element, offset - elementStart, charTable); ASTNode marker = Factory.createSingleLeafElement(TokenType.NEW_LINE_INDENT, DUMMY_IDENTIFIER, charTable, file.getManager()); parent.addChild(marker, space1.getTreeNext()); - return SourceTreeToPsiMap.treeElementToPsi(marker); + PsiElement psiElement = SourceTreeToPsiMap.treeElementToPsi(marker); + return psiElement == null ? null : psiElement.getTextRange(); } public Indent getIndent(String text, FileType fileType) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameDialog.java b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameDialog.java index 561beab8581f..c03611f3fc18 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameDialog.java @@ -91,6 +91,11 @@ public class RenameDialog extends RefactoringDialog { myHelpID = RenamePsiElementProcessor.forElement(psiElement).getHelpID(psiElement); } + @Override + protected boolean hasPreviewButton() { + return RenamePsiElementProcessor.forElement(myPsiElement).showRenamePreviewButton(myPsiElement); + } + protected void dispose() { myNameSuggestionsField.removeDataChangedListener(myNameChangedListener); super.dispose(); diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/RenamePsiElementProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/rename/RenamePsiElementProcessor.java index 3de38efaca85..dde8aeda8421 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/RenamePsiElementProcessor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/RenamePsiElementProcessor.java @@ -139,6 +139,10 @@ public abstract class RenamePsiElementProcessor { } } + public boolean showRenamePreviewButton(final PsiElement psiElement){ + return true; + } + /** * Returns the element to be renamed instead of the element on which the rename refactoring was invoked (for example, a super method * of an inherited method). diff --git a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java index 531dce74dd47..92ee5d5c2917 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndex.java @@ -356,8 +356,9 @@ public class FileBasedIndex implements ApplicationComponent { } myIndexIdToVersionMap.put(name, version); final File versionFile = IndexInfrastructure.getVersionFile(name); + final boolean versionFileExisted = versionFile.exists(); if (isCurrentVersionCorrupted || IndexInfrastructure.versionDiffers(versionFile, version)) { - if (!isCurrentVersionCorrupted) { + if (!isCurrentVersionCorrupted && versionFileExisted) { versionChanged = true; LOG.info("Version has changed for index " + extension.getName() + ". The index will be rebuilt."); } @@ -1162,7 +1163,12 @@ public class FileBasedIndex implements ApplicationComponent { ProgressManager.getInstance().executeNonCancelableSection(new Runnable() { public void run() { try { - final FileContent newFc = new FileContent(vFile, content.getText(), vFile.getCharset()); + final String contentText = content.getText(); + if (isTooLarge(vFile, contentText.length())) { + return; + } + + final FileContent newFc = new FileContent(vFile, contentText, vFile.getCharset()); if (dominantContentFile != null) { dominantContentFile.putUserData(PsiFileImpl.BUILDING_STUB, true); @@ -1819,6 +1825,14 @@ public class FileBasedIndex implements ApplicationComponent { return false; } + private boolean isTooLarge(VirtualFile file, long contentSize) { + if (SingleRootFileViewProvider.isTooLarge(file, contentSize)) { + final FileType type = FileTypeManager.getInstance().getFileTypeByFile(file); + return !myNoLimitCheckTypes.contains(type); + } + return false; + } + public CollectingContentIterator createContentIterator() { return new UnindexedFilesFinder(); } diff --git a/platform/lang-impl/src/com/intellij/util/ui/tree/LanguagePerFileConfigurable.java b/platform/lang-impl/src/com/intellij/util/ui/tree/LanguagePerFileConfigurable.java index 7682362e48b5..9824edbc3e5e 100644 --- a/platform/lang-impl/src/com/intellij/util/ui/tree/LanguagePerFileConfigurable.java +++ b/platform/lang-impl/src/com/intellij/util/ui/tree/LanguagePerFileConfigurable.java @@ -266,7 +266,9 @@ public abstract class LanguagePerFileConfigurable implements SearchableConfig ChangeSomethingAction(@Nullable final VirtualFile file, @Nullable final T t) { super("", "", null); - getTemplatePresentation().setText(t == null ? "Clear" : visualize(t)); + Presentation presentation = getTemplatePresentation(); + presentation.setText(t == null ? "Clear" : visualize(t)); + presentation.setIcon(getIcon(myTreeView.getValues().get(file), t)); myFile = file; myDialect = t; } @@ -278,4 +280,9 @@ public abstract class LanguagePerFileConfigurable implements SearchableConfig protected abstract void chosen(final VirtualFile file, final T t); } } + + @Nullable + protected Icon getIcon(T currentValue, T selectableValue) { + return null; + } } diff --git a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/HistoryDialog.java b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/HistoryDialog.java index 59030d9c0f71..3fbf95bf8a47 100644 --- a/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/HistoryDialog.java +++ b/platform/lvcs-impl/src/com/intellij/history/integration/ui/views/HistoryDialog.java @@ -264,11 +264,11 @@ public abstract class HistoryDialog extends FrameW } public void run() { - if (myProject.isDisposed()) return; + if (isDisposed() || myProject.isDisposed()) return; invokeAndWait(new Runnable() { public void run() { - if (myProject.isDisposed()) return; + if (isDisposed() || myProject.isDisposed()) return; isUpdating = true; updateActions(); @@ -287,7 +287,7 @@ public abstract class HistoryDialog extends FrameW final Runnable finalApply = apply; invokeAndWait(new Runnable() { public void run() { - if (myProject.isDisposed()) return; + if (isDisposed() || myProject.isDisposed()) return; isUpdating = false; if (finalApply != null) { diff --git a/platform/platform-api/src/com/intellij/notification/Notifications.java b/platform/platform-api/src/com/intellij/notification/Notifications.java index 817257d5fb43..2f71c57a27a5 100644 --- a/platform/platform-api/src/com/intellij/notification/Notifications.java +++ b/platform/platform-api/src/com/intellij/notification/Notifications.java @@ -61,15 +61,19 @@ public interface Notifications { FrameStateManager.getInstance().getApplicationActive().doWhenDone(new Runnable() { @Override public void run() { - final MessageBus bus = project == null ? ApplicationManager.getApplication().getMessageBus() : project.getMessageBus(); - if (EventQueue.isDispatchThread()) bus.syncPublisher(TOPIC).notify(notification, defaultDisplayType); - else { - //noinspection SSBasedInspection - SwingUtilities.invokeLater(new Runnable() { - public void run() { - bus.syncPublisher(TOPIC).notify(notification, defaultDisplayType); - } - }); + final MessageBus bus = project == null ? ApplicationManager.getApplication().getMessageBus() : (project.isDisposed() ? null : project.getMessageBus()); + if (bus != null) { + if (EventQueue.isDispatchThread()) { + bus.syncPublisher(TOPIC).notify(notification, defaultDisplayType); + } + else { + //noinspection SSBasedInspection + SwingUtilities.invokeLater(new Runnable() { + public void run() { + bus.syncPublisher(TOPIC).notify(notification, defaultDisplayType); + } + }); + } } } }); diff --git a/platform/platform-api/src/com/intellij/openapi/editor/CaretModel.java b/platform/platform-api/src/com/intellij/openapi/editor/CaretModel.java index 1fdbbf4be789..b74b38223ad6 100644 --- a/platform/platform-api/src/com/intellij/openapi/editor/CaretModel.java +++ b/platform/platform-api/src/com/intellij/openapi/editor/CaretModel.java @@ -17,6 +17,7 @@ package com.intellij.openapi.editor; import com.intellij.openapi.editor.event.CaretListener; import com.intellij.openapi.editor.markup.TextAttributes; +import org.jetbrains.annotations.NotNull; /** * Provides services for moving the caret and retrieving information about caret position. @@ -45,14 +46,14 @@ public interface CaretModel { * * @param pos the position to move to. */ - void moveToLogicalPosition(LogicalPosition pos); + void moveToLogicalPosition(@NotNull LogicalPosition pos); /** * Moves the caret to the specified visual position. * * @param pos the position to move to. */ - void moveToVisualPosition(VisualPosition pos); + void moveToVisualPosition(@NotNull VisualPosition pos); /** * Short hand for calling {@link #moveToOffset(int, boolean)} with 'false' as a second argument. @@ -77,6 +78,7 @@ public interface CaretModel { * * @return the caret position. */ + @NotNull LogicalPosition getLogicalPosition(); /** @@ -84,6 +86,7 @@ public interface CaretModel { * * @return the caret position. */ + @NotNull VisualPosition getVisualPosition(); /** @@ -98,14 +101,14 @@ public interface CaretModel { * * @param listener the listener instance. */ - void addCaretListener(CaretListener listener); + void addCaretListener(@NotNull CaretListener listener); /** * Removes a listener for receiving notifications about caret movement. * * @param listener the listener instance. */ - void removeCaretListener(CaretListener listener); + void removeCaretListener(@NotNull CaretListener listener); /** * @return document offset for the start of the logical line where caret is located diff --git a/platform/platform-api/src/com/intellij/openapi/editor/markup/MarkupModel.java b/platform/platform-api/src/com/intellij/openapi/editor/markup/MarkupModel.java index 27663ad8fa0c..ee0fc33e97a1 100644 --- a/platform/platform-api/src/com/intellij/openapi/editor/markup/MarkupModel.java +++ b/platform/platform-api/src/com/intellij/openapi/editor/markup/MarkupModel.java @@ -80,7 +80,7 @@ public interface MarkupModel extends UserDataHolder { * * @param rangeHighlighter the highlighter to remove. */ - void removeHighlighter(RangeHighlighter rangeHighlighter); + void removeHighlighter(@NotNull RangeHighlighter rangeHighlighter); /** * Removes all highlighter instances. diff --git a/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManager.java b/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManager.java index 0a91e3cff630..6c0a2151931e 100644 --- a/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManager.java +++ b/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManager.java @@ -37,6 +37,21 @@ public abstract class FileEditorManager { */ @NotNull public abstract FileEditor[] openFile(@NotNull VirtualFile file, boolean focusEditor); + + /** + * Opens a file + * + * @param file file to open + * @param focusEditor true if need to focus + * @param searchForSplitter if false then manager will search + * the file through all splitters + * + * @return array of opened editors + */ + @NotNull public FileEditor[] openFile(@NotNull VirtualFile file, boolean focusEditor, boolean searchForSplitter) { + throw new UnsupportedOperationException("Not implemented"); + } + /** * Closes all editors opened for the file. * diff --git a/platform/platform-api/src/com/intellij/openapi/project/DumbService.java b/platform/platform-api/src/com/intellij/openapi/project/DumbService.java index e9f1a4c8e80b..4afcf60bf410 100644 --- a/platform/platform-api/src/com/intellij/openapi/project/DumbService.java +++ b/platform/platform-api/src/com/intellij/openapi/project/DumbService.java @@ -54,6 +54,10 @@ public abstract class DumbService { */ public abstract boolean isDumb(); + public static boolean isDumb(Project project) { + return getInstance(project).isDumb(); + } + /** * Run the runnable when dumb mode ends * @param runnable runnable to run diff --git a/platform/platform-api/src/com/intellij/openapi/startup/StartupManager.java b/platform/platform-api/src/com/intellij/openapi/startup/StartupManager.java index 096bb365b26c..5db16e218253 100644 --- a/platform/platform-api/src/com/intellij/openapi/startup/StartupManager.java +++ b/platform/platform-api/src/com/intellij/openapi/startup/StartupManager.java @@ -40,8 +40,9 @@ public abstract class StartupManager { /** * Registers a CacheUpdater instance that will be used to build initial caches and indices. * Must be called in registerPreStartupActivity or registerStartupActivity + * @param updater to be run */ - public abstract void registerCacheUpdater(CacheUpdater updater); + public abstract void registerCacheUpdater(@NotNull CacheUpdater updater); /** * Registers an activity which is performed during project load while the "Loading Project" @@ -49,7 +50,7 @@ public abstract class StartupManager { * * @param runnable the activity to execute. */ - public abstract void registerStartupActivity(Runnable runnable); + public abstract void registerStartupActivity(@NotNull Runnable runnable); /** * Registers an activity which is performed during project load after the "Loading Project" @@ -57,7 +58,7 @@ public abstract class StartupManager { * * @param runnable the activity to execute. */ - public abstract void registerPostStartupActivity(Runnable runnable); + public abstract void registerPostStartupActivity(@NotNull Runnable runnable); /** * Executes the specified runnable immediately if the initialization of the current project @@ -65,5 +66,5 @@ public abstract class StartupManager { * * @param runnable the activity to execute. */ - public abstract void runWhenProjectIsInitialized(Runnable runnable); + public abstract void runWhenProjectIsInitialized(@NotNull Runnable runnable); } diff --git a/platform/platform-api/src/com/intellij/openapi/wm/IdeFocusManager.java b/platform/platform-api/src/com/intellij/openapi/wm/IdeFocusManager.java index 6e348a398ebd..afa6208cc8d1 100644 --- a/platform/platform-api/src/com/intellij/openapi/wm/IdeFocusManager.java +++ b/platform/platform-api/src/com/intellij/openapi/wm/IdeFocusManager.java @@ -134,4 +134,7 @@ public abstract class IdeFocusManager implements FocusRequestor { public abstract Component getFocusOwner(); public abstract void runOnOwnContext(DataContext context, Runnable runnable); + + @Nullable + public abstract Component getLastFocusedFor(IdeFrame frame); } diff --git a/platform/platform-api/src/com/intellij/openapi/wm/IdeFrame.java b/platform/platform-api/src/com/intellij/openapi/wm/IdeFrame.java index 73fdb6118add..b20488f23029 100644 --- a/platform/platform-api/src/com/intellij/openapi/wm/IdeFrame.java +++ b/platform/platform-api/src/com/intellij/openapi/wm/IdeFrame.java @@ -19,6 +19,7 @@ import com.intellij.openapi.actionSystem.DataKey; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.Nullable; +import javax.swing.*; import java.awt.*; import java.io.File; @@ -38,6 +39,8 @@ public interface IdeFrame { IdeRootPaneNorthExtension getNorthExtension(String key); + JComponent getComponent(); + interface Child extends IdeFrame { IdeFrame getParentFrame(); diff --git a/platform/platform-api/src/com/intellij/openapi/wm/PassThroughtIdeFocusManager.java b/platform/platform-api/src/com/intellij/openapi/wm/PassThroughtIdeFocusManager.java index 2bcfd182d812..9add5eadd668 100644 --- a/platform/platform-api/src/com/intellij/openapi/wm/PassThroughtIdeFocusManager.java +++ b/platform/platform-api/src/com/intellij/openapi/wm/PassThroughtIdeFocusManager.java @@ -97,6 +97,11 @@ public class PassThroughtIdeFocusManager extends IdeFocusManager { runnable.run(); } + @Override + public Component getLastFocusedFor(IdeFrame frame) { + return null; + } + @Override public void suspendKeyProcessingUntil(@NotNull ActionCallback done) { } diff --git a/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java b/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java index b404e6be88b6..4824d168be42 100644 --- a/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java +++ b/platform/platform-api/src/com/intellij/util/ui/ButtonlessScrollBarUI.java @@ -221,6 +221,11 @@ public class ButtonlessScrollBarUI extends BasicScrollBarUI { g.drawRoundRect(hgap, vgap, w, h, 3, 3); } + @Override + public boolean getSupportsAbsolutePositioning() { + return true; + } + protected int adjustThumbWidth(int width) { return width; } diff --git a/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroConfigurable.java b/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroConfigurable.java index 202488e849ab..46574935594b 100644 --- a/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroConfigurable.java +++ b/platform/platform-impl/src/com/intellij/application/options/pathMacros/PathMacroConfigurable.java @@ -67,7 +67,7 @@ public class PathMacroConfigurable implements SearchableConfigurable { } public boolean isModified() { - return myEditor.isModified(); + return myEditor != null && myEditor.isModified(); } public Icon getIcon() { diff --git a/platform/platform-impl/src/com/intellij/diagnostic/DefaultIdeaErrorLogger.java b/platform/platform-impl/src/com/intellij/diagnostic/DefaultIdeaErrorLogger.java index 0cb643701cbc..e0f164468df4 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/DefaultIdeaErrorLogger.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/DefaultIdeaErrorLogger.java @@ -15,9 +15,15 @@ */ package com.intellij.diagnostic; +import com.intellij.notification.Notification; +import com.intellij.notification.NotificationDisplayType; +import com.intellij.notification.NotificationType; +import com.intellij.notification.Notifications; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.diagnostic.ErrorLogger; import com.intellij.openapi.diagnostic.IdeaLoggingEvent; +import com.intellij.openapi.util.SystemInfo; +import com.intellij.util.io.MappingFailedException; import org.jetbrains.annotations.NonNls; import javax.swing.*; @@ -28,6 +34,7 @@ import java.lang.reflect.InvocationTargetException; */ public class DefaultIdeaErrorLogger implements ErrorLogger { private static boolean ourOomOccured = false; + private static boolean mappingFailedNotificationPosted = false; @NonNls private static final String FATAL_ERROR_NOTIFICATION_PROPERTY = "idea.fatal.error.notification"; @NonNls private static final String DISABLED_VALUE = "disabled"; @NonNls private static final String ENABLED_VALUE = "enabled"; @@ -39,7 +46,8 @@ public class DefaultIdeaErrorLogger implements ErrorLogger { return notificationEnabled || !(IdeErrorsDialog.getSubmitter(event.getThrowable()) instanceof ITNReporter) || ApplicationManagerEx.getApplicationEx().isInternal() || - event.getThrowable() instanceof OutOfMemoryError; + event.getThrowable() instanceof OutOfMemoryError || + event.getThrowable() instanceof MappingFailedException; } /** @@ -50,6 +58,9 @@ public class DefaultIdeaErrorLogger implements ErrorLogger { if (event.getThrowable() instanceof OutOfMemoryError) { processOOMError(event); } + else if (event.getThrowable() instanceof MappingFailedException) { + processMappingFailed(event); + } else if (!ourOomOccured) { MessagePool.getInstance().addIdeFatalMessage(event); } @@ -62,7 +73,7 @@ public class DefaultIdeaErrorLogger implements ErrorLogger { /** * @noinspection CallToPrintStackTrace */ - private void processOOMError(final IdeaLoggingEvent event) throws InterruptedException, InvocationTargetException { + private static void processOOMError(final IdeaLoggingEvent event) throws InterruptedException, InvocationTargetException { ourOomOccured = true; event.getThrowable().printStackTrace(); @@ -76,4 +87,15 @@ public class DefaultIdeaErrorLogger implements ErrorLogger { } }); } + + private static void processMappingFailed(final IdeaLoggingEvent event) throws InterruptedException, InvocationTargetException { + if (!mappingFailedNotificationPosted && SystemInfo.isWindows && SystemInfo.is32Bit) { + mappingFailedNotificationPosted = true; + final String exceptionMessage = event.getThrowable().getMessage(); + final String text = exceptionMessage + + "
Possible cause: unable to allocate continuous memory chunk of necessary size.
Reducing JVM's maximum heap size (-Xmx) may help."; + Notifications.Bus.notify(new Notification("Memory", "Memory Mapping Failed", text, NotificationType.WARNING), NotificationDisplayType.BALLOON, null); + } + } + } diff --git a/platform/platform-impl/src/com/intellij/diagnostic/IdeErrorsDialog.java b/platform/platform-impl/src/com/intellij/diagnostic/IdeErrorsDialog.java index 713593416790..f06ec030e872 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/IdeErrorsDialog.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/IdeErrorsDialog.java @@ -148,11 +148,11 @@ public class IdeErrorsDialog extends DialogWrapper implements MessagePoolListene DefaultActionGroup group = new DefaultActionGroup(); BackAction back = new BackAction(); - back.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)), getRootPane()); + back.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.ALT_DOWN_MASK)), getRootPane()); group.add(back); ForwardAction forward = new ForwardAction(); - forward.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0)), getRootPane()); + forward.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.ALT_DOWN_MASK)), getRootPane()); group.add(forward); group.add(new ClearFatalsAction()); diff --git a/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java b/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java index ea5ebcc8fd0d..63fee15836bd 100644 --- a/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java +++ b/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java @@ -16,10 +16,7 @@ package com.intellij.ide; import com.intellij.ide.impl.ProjectUtil; -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.actionSystem.Separator; +import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.project.DumbAware; @@ -29,15 +26,14 @@ import com.intellij.openapi.project.ProjectManagerAdapter; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.SystemInfo; +import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.messages.MessageBus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.event.InputEvent; import java.io.*; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; +import java.util.*; /** * @author yole @@ -143,6 +139,8 @@ public abstract class RecentProjectsManagerBase implements PersistentStateCompon Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); ArrayList actions = new ArrayList(); + final Map map = new LinkedHashMap(); + final List paths = new ArrayList(); synchronized (myState) { outer: for (String recentPath : myState.recentPaths) { @@ -153,10 +151,16 @@ public abstract class RecentProjectsManagerBase implements PersistentStateCompon } } - actions.add(new ReopenProjectAction(recentPath)); + final String projectName = getProjectName(recentPath); + map.put(projectName, map.containsKey(projectName) ? map.get(projectName) + 1 : 1); + paths.add(recentPath); } } + for (final String path : paths) { + final String projectName = getProjectName(path); + actions.add(map.get(projectName) > 1 ? new ReopenProjectAction(path, path) : new ReopenProjectAction(path, projectName)); + } if (actions.size() == 0) { return new AnAction[0]; @@ -218,51 +222,58 @@ public abstract class RecentProjectsManagerBase implements PersistentStateCompon } } - private class ReopenProjectAction extends AnAction implements DumbAware { - private final String myProjectPath; - - public ReopenProjectAction(String projectPath) { - myProjectPath = projectPath; - - String _text = projectPath; - final String projectName = getProjectName(projectPath); - if (projectName != null) { - _text = String.format("%s (%s)", projectPath, projectName); - } - - getTemplatePresentation().setText(_text, false); - } - - @Nullable - private String getProjectName(String path) { - if (new File(path).isDirectory()) { - final File nameFile = new File(new File(path, Project.DIRECTORY_STORE_FOLDER), ".name"); - if (nameFile.exists()) { - BufferedReader in = null; - try { - in = new BufferedReader(new InputStreamReader(new FileInputStream(nameFile), "UTF-8")); - final String name = in.readLine(); - if (name != null && name.length() > 0) return name.trim(); - } - catch (IOException e) { - // ignore - } - finally { - if (in != null) { - try { - in.close(); - } - catch (IOException e) { - // ignore - } + @Nullable + private static String getProjectName(String path) { + final File file = new File(path); + if (file.isDirectory()) { + final File nameFile = new File(new File(path, Project.DIRECTORY_STORE_FOLDER), ".name"); + if (nameFile.exists()) { + BufferedReader in = null; + try { + in = new BufferedReader(new InputStreamReader(new FileInputStream(nameFile), "UTF-8")); + final String name = in.readLine(); + if (name != null && name.length() > 0) return name.trim(); + } + catch (IOException e) { + // ignore + } + finally { + if (in != null) { + try { + in.close(); + } + catch (IOException e) { + // ignore } } } + } else { + return file.getName(); + } + } else { + return FileUtil.getNameWithoutExtension(file.getName()); + } + + return null; + } + + private class ReopenProjectAction extends AnAction implements DumbAware { + private final String myProjectPath; + + public ReopenProjectAction(final String projectPath, final String projectName) { + myProjectPath = projectPath; + + String _text = projectPath; + if (projectName != null) { + _text = String.format("%s", projectName); } - return null; + final Presentation presentation = getTemplatePresentation(); + presentation.setText(_text, false); + presentation.setDescription(projectPath); } + public void actionPerformed(AnActionEvent e) { final int modifiers = e.getModifiers(); final boolean forceOpenInNewFrame = (modifiers & InputEvent.CTRL_MASK) != 0 || (modifiers & InputEvent.SHIFT_MASK) != 0; diff --git a/platform/platform-impl/src/com/intellij/ide/actions/CodeEditorActionGroup.java b/platform/platform-impl/src/com/intellij/ide/actions/CodeEditorActionGroup.java deleted file mode 100644 index 43597f77ac24..000000000000 --- a/platform/platform-impl/src/com/intellij/ide/actions/CodeEditorActionGroup.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.ide.actions; - -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.DefaultActionGroup; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.actionSystem.Presentation; -import com.intellij.openapi.project.DumbAware; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.wm.ToolWindowManager; - -public class CodeEditorActionGroup extends DefaultActionGroup implements DumbAware { - public CodeEditorActionGroup() { - super(); - } - - public void update(AnActionEvent event){ - Presentation presentation = event.getPresentation(); - Project project = PlatformDataKeys.PROJECT.getData(event.getDataContext()); - if (project == null) { - presentation.setVisible(false); - return; - } - boolean active = ToolWindowManager.getInstance(project).isEditorComponentActive(); - presentation.setVisible(active); - } -} \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java b/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java index 4c39bbe0b6f9..d9ed5b2d62a6 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java @@ -21,8 +21,11 @@ import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; +import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; +import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileEditor.impl.EditorHistoryManager; +import com.intellij.openapi.fileEditor.impl.EditorWindow; import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; @@ -102,11 +105,13 @@ public class Switcher extends AnAction implements DumbAware { public void actionPerformed(AnActionEvent e) { final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); if (project == null) return; + boolean selectFirstItem = false; if (SWITCHER == null) { synchronized (Switcher.class) { if (SWITCHER == null) { SWITCHER = new SwitcherPanel(project); FeatureUsageTracker.getInstance().triggerFeatureUsed(SWITCHER_FEATURE_ID); + selectFirstItem = !FileEditorManagerEx.getInstanceEx(project).hasOpenedFile(); } } } @@ -114,7 +119,11 @@ public class Switcher extends AnAction implements DumbAware { if (e.getInputEvent().isShiftDown()) { SWITCHER.goBack(); } else { - SWITCHER.goForward(); + if (selectFirstItem) { + SWITCHER.files.setSelectedIndex(0); + } else { + SWITCHER.goForward(); + } } } @@ -128,6 +137,7 @@ public class Switcher extends AnAction implements DumbAware { final JLabel pathLabel = new JLabel(" "); final JPanel descriptions; final Project project; + final Map files2editors; SwitcherPanel(Project project) { super(new BorderLayout(0, 0)); @@ -212,11 +222,20 @@ public class Switcher extends AnAction implements DumbAware { separator.setBackground(Color.WHITE); final FileEditorManager editorManager = FileEditorManager.getInstance(project); - final VirtualFile[] openFiles = editorManager.getOpenFiles(); - - try { - Arrays.sort(openFiles, new RecentFilesComparator(project)); - } catch (Exception e) {// IndexNotReadyException + final FileEditor[] allEditors = editorManager.getAllEditors(); + files2editors = new HashMap(); + for (FileEditor editor : allEditors) { + files2editors.put(((FileEditorManagerImpl)editorManager).getFile(editor), editor); + } + final VirtualFile[] recentFiles = EditorHistoryManager.getInstance(project).getFiles(); + final ArrayList openFiles = new ArrayList(); + for (VirtualFile recentFile : recentFiles) { + openFiles.add(0, recentFile); + } + final ArrayList tmp = new ArrayList(files2editors.keySet()); + tmp.removeAll(openFiles); + for (VirtualFile virtualFile : tmp) { + openFiles.add(0, virtualFile); } final DefaultListModel filesModel = new DefaultListModel(); @@ -315,7 +334,15 @@ public class Switcher extends AnAction implements DumbAware { return true; } }).createPopup(); - myPopup.showInCenterOf(ideFrame.getContentPane()); + Component comp = null; + final EditorWindow result = FileEditorManagerEx.getInstanceEx(project).getActiveWindow().getResult(); + if (result != null) { + comp = result.getOwner(); + } + if (comp == null) { + comp = ideFrame.getContentPane(); + } + myPopup.showInCenterOf(comp); } private int getModifiers(ShortcutSet shortcutSet) { @@ -494,7 +521,8 @@ public class Switcher extends AnAction implements DumbAware { ((ToolWindow)value).activate(null, true, true); } else if (value instanceof VirtualFile) { - FileEditorManager.getInstance(project).openFile((VirtualFile)value, true); + final VirtualFile file = (VirtualFile)value; + FileEditorManager.getInstance(project).openFile(file, true, true); } } diff --git a/platform/platform-impl/src/com/intellij/ide/actions/WindowAction.java b/platform/platform-impl/src/com/intellij/ide/actions/WindowAction.java index 67bd4480db7a..a61a85fd5d4b 100644 --- a/platform/platform-impl/src/com/intellij/ide/actions/WindowAction.java +++ b/platform/platform-impl/src/com/intellij/ide/actions/WindowAction.java @@ -17,6 +17,7 @@ package com.intellij.ide.actions; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; @@ -25,7 +26,7 @@ import com.intellij.openapi.wm.ex.WindowManagerEx; import javax.swing.*; import java.awt.*; -public abstract class WindowAction extends AnAction { +public abstract class WindowAction extends AnAction implements DumbAware { public static final String NO_WINDOW_ACTIONS = "no.window.actions"; diff --git a/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java index 9544ca3b911b..31f5fb82b90e 100644 --- a/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java @@ -23,14 +23,16 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.project.*; +import com.intellij.openapi.project.DumbAwareRunnable; +import com.intellij.openapi.project.DumbService; +import com.intellij.openapi.project.DumbServiceImpl; +import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFileManager; -import com.intellij.util.containers.CollectionFactory; import com.intellij.util.io.storage.HeavyProcessLatch; +import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; -import javax.swing.*; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; @@ -41,14 +43,15 @@ public class StartupManagerImpl extends StartupManagerEx { private final List myPreStartupActivities = Collections.synchronizedList(new ArrayList()); private final List myStartupActivities = new ArrayList(); - private final List myPostStartupActivities = Collections.synchronizedList(new ArrayList()); + + private final List myDumbAwarePostStartupActivities = Collections.synchronizedList(new ArrayList()); + private final List myNotDumbAwarePostStartupActivities = Collections.synchronizedList(new ArrayList()); + private boolean myPostStartupActivitiesPassed = false; // guarded by this private final List myCacheUpdaters = new LinkedList(); - private volatile boolean myPreStartupActivitiesPassed = false; private volatile boolean myStartupActivitiesRunning = false; private volatile boolean myStartupActivitiesPassed = false; - private volatile boolean myPostStartupActivitiesPassed = false; private final Project myProject; @@ -63,19 +66,19 @@ public class StartupManagerImpl extends StartupManagerEx { } @Override - public void registerStartupActivity(Runnable runnable) { + public void registerStartupActivity(@NotNull Runnable runnable) { LOG.assertTrue(!myStartupActivitiesPassed, "Registering startup activity that will never be run"); myStartupActivities.add(runnable); } @Override - public synchronized void registerPostStartupActivity(Runnable runnable) { + public synchronized void registerPostStartupActivity(@NotNull Runnable runnable) { LOG.assertTrue(!myPostStartupActivitiesPassed, "Registering post-startup activity that will never be run"); - myPostStartupActivities.add(runnable); + (DumbService.isDumbAware(runnable) ? myDumbAwarePostStartupActivities : myNotDumbAwarePostStartupActivities).add(runnable); } @Override - public void registerCacheUpdater(CacheUpdater updater) { + public void registerCacheUpdater(@NotNull CacheUpdater updater) { LOG.assertTrue(!myStartupActivitiesPassed, CacheUpdater.class.getSimpleName() + " must be registered before startup activity finished"); myCacheUpdaters.add(updater); } @@ -91,7 +94,7 @@ public class StartupManagerImpl extends StartupManagerEx { } @Override - public boolean postStartupActivityPassed() { + public synchronized boolean postStartupActivityPassed() { return myPostStartupActivitiesPassed; } @@ -119,31 +122,22 @@ public class StartupManagerImpl extends StartupManagerEx { } public synchronized void runPostStartupActivities() { - Application app = ApplicationManager.getApplication(); + final Application app = ApplicationManager.getApplication(); app.assertIsDispatchThread(); if (myPostStartupActivitiesPassed) return; - final List dumbAware = CollectionFactory.arrayList(); - final List nonDumbAware = CollectionFactory.arrayList(); - - for (Runnable each : myPostStartupActivities) { - if (DumbService.isDumbAware(each)) { - dumbAware.add(each); - } - else { - nonDumbAware.add(each); - } - } - - runActivities(dumbAware); + runActivities(myDumbAwarePostStartupActivities); DumbService.getInstance(myProject).runWhenSmart(new Runnable() { public void run() { - if (myProject.isDisposed()) return; - runActivities(nonDumbAware); + synchronized (StartupManagerImpl.this) { + app.assertIsDispatchThread(); + if (myProject.isDisposed()) return; + runActivities(myDumbAwarePostStartupActivities); // they can register activities while in the dumb mode + runActivities(myNotDumbAwarePostStartupActivities); - myPostStartupActivitiesPassed = true; - myPostStartupActivities.clear(); + myPostStartupActivitiesPassed = true; + } } }); @@ -164,7 +158,7 @@ public class StartupManagerImpl extends StartupManagerEx { } } - private static void runActivities(final List activities) { + private static void runActivities(@NotNull List activities) { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); while (!activities.isEmpty()) { final Runnable runnable = activities.remove(0); @@ -182,7 +176,7 @@ public class StartupManagerImpl extends StartupManagerEx { } } - public void runWhenProjectIsInitialized(final Runnable action) { + public synchronized void runWhenProjectIsInitialized(@NotNull final Runnable action) { final Runnable runnable; final Application application = ApplicationManager.getApplication(); @@ -201,20 +195,16 @@ public class StartupManagerImpl extends StartupManagerEx { }; } - if (myProject.isInitialized() || (application.isUnitTestMode() && myPostStartupActivitiesPassed)) { - // in tests which simulate project opening, post-startup activities could have been run already. Then we should act as if the project was initialized - if (application.isDispatchThread()) { - runnable.run(); - } - else { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (!myProject.isDisposed()) { - runnable.run(); - } + if (myProject.isInitialized() || application.isUnitTestMode() && myPostStartupActivitiesPassed) { + // in tests which simulate project opening, post-startup activities could have been run already. + // Then we should act as if the project was initialized + UIUtil.invokeLaterIfNeeded(new Runnable() { + public void run() { + if (!myProject.isDisposed()) { + runnable.run(); } - }); - } + } + }); } else { registerPostStartupActivity(runnable); @@ -222,10 +212,11 @@ public class StartupManagerImpl extends StartupManagerEx { } @TestOnly - public void prepareForNextTest() { + public synchronized void prepareForNextTest() { myPreStartupActivities.clear(); myStartupActivities.clear(); - myPostStartupActivities.clear(); + myDumbAwarePostStartupActivities.clear(); + myNotDumbAwarePostStartupActivities.clear(); myCacheUpdaters.clear(); myPreStartupActivitiesPassed = false; @@ -235,10 +226,11 @@ public class StartupManagerImpl extends StartupManagerEx { } @TestOnly - public void checkCleared() { + public synchronized void checkCleared() { try { assert myStartupActivities.isEmpty() : "Activities: " + myStartupActivities; - assert myPostStartupActivities.isEmpty() : "Post Activities: " + myPostStartupActivities; + assert myDumbAwarePostStartupActivities.isEmpty() : "DumbAware Post Activities: " + myDumbAwarePostStartupActivities; + assert myNotDumbAwarePostStartupActivities.isEmpty() : "Post Activities: " + myNotDumbAwarePostStartupActivities; assert myPreStartupActivities.isEmpty() : "Pre Activities: " + myPreStartupActivities; } finally { diff --git a/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomizableActionsPanel.form b/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomizableActionsPanel.form index 5b0b02e62987..9862f7b9142b 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomizableActionsPanel.form +++ b/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomizableActionsPanel.form @@ -1,6 +1,6 @@

- + @@ -8,17 +8,17 @@ - + - + - + - + @@ -82,12 +82,20 @@ - + - + + + + + + + + + diff --git a/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomizableActionsPanel.java b/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomizableActionsPanel.java index dca05d5c1783..ab28bdf26ec8 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomizableActionsPanel.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/customization/CustomizableActionsPanel.java @@ -29,7 +29,6 @@ import com.intellij.openapi.keymap.impl.ui.Group; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; -import com.intellij.openapi.ui.DetailsComponent; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.TextFieldWithBrowseButton; @@ -60,9 +59,8 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; -import java.util.HashSet; +import java.util.*; import java.util.List; -import java.util.Set; /** * User: anna @@ -90,10 +88,9 @@ public class CustomizableActionsPanel { - private JPanel myDetailsPanel; + private JButton myRestoreAllDefaultButton; private JButton myRestoreDefaultButton; public static final Icon FULLISH_ICON = IconLoader.getIcon("/toolbar/unknown.png"); - private DetailsComponent myDetailsComponent; public CustomizableActionsPanel() { @@ -144,6 +141,7 @@ public class CustomizableActionsPanel { } myMoveActionUpButton.setEnabled(isMoveSupported(myActionsTree, -1)); myMoveActionDownButton.setEnabled(isMoveSupported(myActionsTree, 1)); + myRestoreDefaultButton.setEnabled(!findActionsUnderSelection().isEmpty()); } }); @@ -178,7 +176,7 @@ public class CustomizableActionsPanel { myEditIconButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - myRestoreDefaultButton.setEnabled(true); + myRestoreAllDefaultButton.setEnabled(true); final List expandedPaths = TreeUtil.collectExpandedPaths(myActionsTree); final TreePath selectionPath = myActionsTree.getLeadSelectionPath(); if (selectionPath != null) { @@ -270,10 +268,25 @@ public class CustomizableActionsPanel { } }); - myRestoreDefaultButton.addActionListener(new ActionListener() { + myRestoreAllDefaultButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { mySelectedSchema.copyFrom(new CustomActionsSchema()); patchActionsTreeCorrespondingToSchema(root); + myRestoreAllDefaultButton.setEnabled(false); + } + }); + + myRestoreDefaultButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + final List otherActions = new ArrayList(mySelectedSchema.getActions()); + otherActions.removeAll(findActionsUnderSelection()); + mySelectedSchema.copyFrom(new CustomActionsSchema()); + for (ActionUrl otherAction : otherActions) { + mySelectedSchema.addAction(otherAction); + } + final List treePaths = TreeUtil.collectExpandedPaths(myActionsTree); + patchActionsTreeCorrespondingToSchema(root); + restorePathsAfterTreeOptimization(treePaths); myRestoreDefaultButton.setEnabled(false); } }); @@ -283,18 +296,32 @@ public class CustomizableActionsPanel { myTreeExpansionMonitor = TreeExpansionMonitor.install(myActionsTree); } + private List findActionsUnderSelection() { + final ArrayList actions = new ArrayList(); + final TreePath[] selectionPaths = myActionsTree.getSelectionPaths(); + if (selectionPaths != null) { + for (TreePath path : selectionPaths) { + final ActionUrl selectedUrl = CustomizationUtil.getActionUrl(path, ActionUrl.MOVE); + final ArrayList selectedGroupPath = new ArrayList(selectedUrl.getGroupPath()); + final Object component = selectedUrl.getComponent(); + if (component instanceof Group) { + selectedGroupPath.add(((Group)component).getName()); + for (ActionUrl action : mySelectedSchema.getActions()) { + final ArrayList groupPath = action.getGroupPath(); + final int idx = Collections.indexOfSubList(groupPath, selectedGroupPath); + if (idx > -1) { + actions.add(action); + } + } + } + } + } + return actions; + } + private void addCustomizedAction(ActionUrl url) { mySelectedSchema.addAction(url); - myRestoreDefaultButton.setEnabled(true); - } - - public void initUi() { - myDetailsComponent = new DetailsComponent(); - myDetailsComponent.setContent(myDetailsPanel); - } - - public DetailsComponent getDetails() { - return myDetailsComponent; + myRestoreAllDefaultButton.setEnabled(true); } private void editToolbarIcon(String actionId, DefaultMutableTreeNode node) { @@ -401,7 +428,7 @@ public class CustomizableActionsPanel { mySelectedSchema = new CustomActionsSchema(); mySelectedSchema.copyFrom(CustomActionsSchema.getInstance()); patchActionsTreeCorrespondingToSchema((DefaultMutableTreeNode)myActionsTree.getModel().getRoot()); - myRestoreDefaultButton.setEnabled(mySelectedSchema.isModified(new CustomActionsSchema())); + myRestoreAllDefaultButton.setEnabled(mySelectedSchema.isModified(new CustomActionsSchema())); } public boolean isModified() { diff --git a/platform/platform-impl/src/com/intellij/openapi/components/impl/ComponentManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/components/impl/ComponentManagerImpl.java index 8186d5401b87..a2d6e5abdbc4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/components/impl/ComponentManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/components/impl/ComponentManagerImpl.java @@ -652,7 +652,14 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements componentInstance = super.getComponentInstance(picoContainer); if (!myInitialized) { - if (myInitializing) LOG.error(new Throwable("Cyclic component initialization: " + componentKey)); + if (myInitializing) { + if (myConfig.pluginDescriptor != null) { + LOG.error(new PluginException("Cyclic component initialization: " + componentKey, myConfig.pluginDescriptor.getPluginId())); + } + else { + LOG.error(new Throwable("Cyclic component initialization: " + componentKey)); + } + } myInitializing = true; myComponentsRegistry.registerComponentInstance(componentInstance); initComponent(componentInstance); diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/DiffManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/DiffManagerImpl.java index 043258a01e1c..7c1e4fa0aa63 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/DiffManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/external/DiffManagerImpl.java @@ -38,6 +38,7 @@ import org.jetbrains.annotations.NotNull; import java.awt.*; import java.util.ArrayList; +import java.util.Arrays; public class DiffManagerImpl extends DiffManager implements JDOMExternalizable { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.impl.external.DiffManagerImpl"); @@ -86,7 +87,7 @@ public class DiffManagerImpl extends DiffManager implements JDOMExternalizable { public DiffTool getIdeaDiffTool() { return INTERNAL_DIFF; } public DiffTool getDiffTool() { - DiffTool[] standardTools = new DiffTool[]{ + DiffTool[] standardTools = { ExtCompareFolders.INSTANCE, ExtCompareFiles.INSTANCE, INTERNAL_DIFF, @@ -94,10 +95,7 @@ public class DiffManagerImpl extends DiffManager implements JDOMExternalizable { BinaryDiffTool.INSTANCE }; ArrayList allTools = new ArrayList(myAdditionTools); - for (int i = 0; i < standardTools.length; i++) { - DiffTool standardTool = standardTools[i]; - allTools.add(standardTool); - } + allTools.addAll(Arrays.asList(standardTools)); return new CompositeDiffTool(allTools); } @@ -133,8 +131,7 @@ public class DiffManagerImpl extends DiffManager implements JDOMExternalizable { final String policyName = element.getAttributeValue(COMPARISON_POLICY_ATTR_NAME); if (policyName != null) { ComparisonPolicy[] policies = ComparisonPolicy.getAllInstances(); - for (int i = 0; i < policies.length; i++) { - ComparisonPolicy policy = policies[i]; + for (ComparisonPolicy policy : policies) { if (policy.getName().equals(policyName)) { myComparisonPolicy = policy; break; diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/ex/MarkupModelEx.java b/platform/platform-impl/src/com/intellij/openapi/editor/ex/MarkupModelEx.java index 99f7fdb96808..21801c1691b3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/ex/MarkupModelEx.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/ex/MarkupModelEx.java @@ -51,7 +51,7 @@ public interface MarkupModelEx extends MarkupModel, Iterable int endOffset, int layer, TextAttributes textAttributes, - HighlighterTargetArea targetArea, + @NotNull HighlighterTargetArea targetArea, boolean isPersistent, Consumer changeAttributesAction); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/SegmentArray.java b/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/SegmentArray.java index 520e2b9c8da1..9e37fb62028a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/SegmentArray.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/ex/util/SegmentArray.java @@ -238,14 +238,14 @@ public class SegmentArray { public int getSegmentStart(int index) { if (index < 0 || index >= mySegmentCount) { - throw new IndexOutOfBoundsException("Wrong line: " + index); + throw new IndexOutOfBoundsException("Wrong line: " + index + ". Available lines count: " + mySegmentCount); } return myStarts[index]; } public int getSegmentEnd(int index) { if (index < 0 || index >= mySegmentCount) { - throw new IndexOutOfBoundsException("Wrong line: " + index); + throw new IndexOutOfBoundsException("Wrong line: " + index + ". Available lines count: " + mySegmentCount); } return myEnds[index]; } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java index 72f79aad4f61..3ce855b2c0ba 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java @@ -32,7 +32,10 @@ import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.event.CaretEvent; import com.intellij.openapi.editor.event.CaretListener; import com.intellij.openapi.editor.event.DocumentEvent; -import com.intellij.openapi.editor.ex.*; +import com.intellij.openapi.editor.ex.DocumentBulkUpdateListener; +import com.intellij.openapi.editor.ex.DocumentEx; +import com.intellij.openapi.editor.ex.EditorGutterComponentEx; +import com.intellij.openapi.editor.ex.PrioritizedDocumentListener; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.editor.impl.event.DocumentEventImpl; import com.intellij.openapi.editor.impl.softwrap.SoftWrapHelper; @@ -40,6 +43,7 @@ import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.CharArrayUtil; +import org.jetbrains.annotations.NotNull; import java.awt.*; import java.util.List; @@ -92,7 +96,7 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, } } - public void moveToVisualPosition(VisualPosition pos) { + public void moveToVisualPosition(@NotNull VisualPosition pos) { assertIsDispatchThread(); validateCallContext(); int column = pos.column; @@ -293,7 +297,7 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, } } - public void moveToLogicalPosition(LogicalPosition pos) { + public void moveToLogicalPosition(@NotNull LogicalPosition pos) { moveToLogicalPosition(pos, false); } @@ -423,6 +427,7 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, } } + @NotNull public LogicalPosition getLogicalPosition() { validateCallContext(); return myLogicalCaret; @@ -432,6 +437,7 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, LOG.assertTrue(!myIsInUpdate, "Caret model is in its update process. All requests are illegal at this point."); } + @NotNull public VisualPosition getVisualPosition() { validateCallContext(); return myVisibleCaret; @@ -450,11 +456,11 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, return myVisualLineEnd; } - public void addCaretListener(CaretListener listener) { + public void addCaretListener(@NotNull CaretListener listener) { myCaretListeners.add(listener); } - public void removeCaretListener(CaretListener listener) { + public void removeCaretListener(@NotNull CaretListener listener) { boolean success = myCaretListeners.remove(listener); LOG.assertTrue(success); } @@ -537,7 +543,7 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, return EditorDocumentPriorities.CARET_MODEL; } - private void setCurrentLogicalCaret(LogicalPosition position) { + private void setCurrentLogicalCaret(@NotNull LogicalPosition position) { myLogicalCaret = position; myCaretInfo = createVerticalInfo(position); } @@ -545,6 +551,9 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, private VerticalInfo createVerticalInfo(LogicalPosition position) { Document document = myEditor.getDocument(); int logicalLine = position.line; + if (logicalLine >= document.getLineCount()) { + logicalLine = Math.max(0, document.getLineCount() - 1); + } int startOffset = document.getLineStartOffset(logicalLine); int endOffset = document.getLineEndOffset(logicalLine); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/DocumentImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/DocumentImpl.java index 1759c91a9a98..a23b1ed2fe0e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/DocumentImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/DocumentImpl.java @@ -212,19 +212,12 @@ public class DocumentImpl extends UserDataHolderBase implements DocumentEx { public boolean removeRangeMarker(@NotNull RangeMarkerEx rangeMarker) { ApplicationManagerEx.getApplicationEx().assertReadAccessToDocumentsAllowed(); - synchronized(myRangeMarkers) { - return myRangeMarkers.remove(rangeMarker); - } + return myRangeMarkers.remove(rangeMarker); } public void addRangeMarker(@NotNull RangeMarkerEx rangeMarker) { ApplicationManagerEx.getApplicationEx().assertReadAccessToDocumentsAllowed(); - synchronized(myRangeMarkers) { - RangeMarkerImpl marker = (RangeMarkerImpl)rangeMarker; - marker.setValid(true); - marker.myNode = myRangeMarkers.add(rangeMarker); - myRangeMarkers.checkMax(true); - } + myRangeMarkers.add(rangeMarker); } @TestOnly @@ -462,9 +455,9 @@ public class DocumentImpl extends UserDataHolderBase implements DocumentEx { return null; // suppress events in shutdown hook } DocumentEvent event = new DocumentEventImpl(this, offset, oldString, newString, myModificationStamp, wholeTextReplaced); - //System.out.printf("%nbefore change: offset=%d, old text='%n%s%n', new text='%n%s%n', document modification stamp=%d%nDocument:'%s'%n", - // event.getOffset(), event.getOldFragment(), event.getNewFragment(), event.getDocument().getModificationStamp(), - // event.getDocument().getText()); + //System.out.printf("%nbefore change: offset=%d, old text='%s', new text='%s'%n document: id=%d, modification stamp=%d%nDocument:'%s'%n", + // event.getOffset(), event.getOldFragment(), event.getNewFragment(), System.identityHashCode(this), + // getModificationStamp(), getText()); DocumentListener[] listeners = getCachedListeners(); for (int i = listeners.length - 1; i >= 0; i--) { @@ -481,8 +474,8 @@ public class DocumentImpl extends UserDataHolderBase implements DocumentEx { } private void changedUpdate(DocumentEvent event, long newModificationStamp) { - //System.out.printf("after change: new modification stamp=%d%ndocument='%s'%n", event.getDocument().getModificationStamp(), - // event.getDocument().getText()); + //System.out.printf("after change: document id=%d, new modification stamp=%d%ndocument='%s'%n", System.identityHashCode(this), + // getModificationStamp(), getText()); if (ShutDownTracker.isShutdownHookRunning()) { return; // suppress events in shutdown hook } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java index 5f33b7b257a4..148286f8984c 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java @@ -149,9 +149,11 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); try { - paintFoldingBackground(g); - paintLineMarkers(g, clip); - paintFoldingTree(g, clip); + int firstVisibleOffset = myEditor.logicalPositionToOffset(myEditor.xyToLogicalPosition(new Point(0, clip.y - myEditor.getLineHeight()))); + int lastVisibleOffset = myEditor.logicalPositionToOffset(myEditor.xyToLogicalPosition(new Point(0, clip.y + clip.height + myEditor.getLineHeight()))); + paintFoldingBackground(g, clip, firstVisibleOffset, lastVisibleOffset); + paintLineMarkers(g, clip, firstVisibleOffset, lastVisibleOffset); + paintFoldingTree(g, clip, firstVisibleOffset, lastVisibleOffset); } finally { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, hint); @@ -163,6 +165,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse ((ApplicationImpl)ApplicationManager.getApplication()).editorPaintFinish(); } } + private void processClose(final MouseEvent e) { final IdeEventQueue queue = IdeEventQueue.getInstance(); @@ -240,19 +243,19 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse UIUtil.drawVDottedLine((Graphics2D)g, getAnnotationsAreaOffset() + w - 1, clip.y, clip.y + clip.height, null, getOutlineColor(false)); } - private void paintFoldingTree(Graphics g, Rectangle clip) { + private void paintFoldingTree(Graphics g, Rectangle clip, int firstVisibleOffset, int lastVisibleOffset) { if (isFoldingOutlineShown()) { - paintFoldingTree((Graphics2D)g); + doPaintFoldingTree((Graphics2D)g, clip, firstVisibleOffset, lastVisibleOffset); } else { UIUtil.drawVDottedLine((Graphics2D)g, clip.x + clip.width -1, clip.y, clip.y + clip.height, null, getOutlineColor(false)); } } - private void paintLineMarkers(Graphics g, Rectangle clip) { + private void paintLineMarkers(Graphics g, Rectangle clip, int firstVisibleOffset, int lastVisibleOffset) { if (isLineMarkersShown()) { paintBackground(g, clip, getLineMarkerAreaOffset(), getLineMarkerAreaWidth()); - paintGutterRenderers(g); + paintGutterRenderers(g, firstVisibleOffset, lastVisibleOffset); } } @@ -278,7 +281,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse paintBackground(g, clip, getLineNumberAreaOffset(), getLineNumberAreaWidth()); int x = getLineNumberAreaOffset() + getLineNumberAreaWidth() - 2; UIUtil.drawVDottedLine((Graphics2D)g, x, clip.y, clip.y + clip.height, null, getOutlineColor(false)); - paintLineNumbers(g); + doPaintLineNumbers(g, clip); } } @@ -290,11 +293,10 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse return myBackgroundColor; } - private void paintLineNumbers(Graphics g) { + private void doPaintLineNumbers(Graphics g, Rectangle clip) { if (!isLineNumbersShown()) { return; } - Rectangle clip = g.getClipBounds(); int lineHeight = myEditor.getLineHeight(); int startLineNumber = clip.y / lineHeight; int endLineNumber = (clip.y + clip.height) / lineHeight + 1; @@ -490,14 +492,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse (isFoldingOutlineShown() ? 0 : getFoldingAnchorWidth() / 2); } - private void paintGutterRenderers(final Graphics g) { - Rectangle clip = g.getClipBounds(); - - int firstVisibleOffset = myEditor.logicalPositionToOffset( - myEditor.xyToLogicalPosition(new Point(0, clip.y - myEditor.getLineHeight()))); - int lastVisibleOffset = myEditor.logicalPositionToOffset( - myEditor.xyToLogicalPosition(new Point(0, clip.y + clip.height + myEditor.getLineHeight()))); - + private void paintGutterRenderers(final Graphics g, int firstVisibleOffset, int lastVisibleOffset) { Graphics2D g2 = (Graphics2D)g; Object hint = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); @@ -656,19 +651,12 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse return new VisualPosition(myEditor.offsetToVisualPosition(offset).line, 0); } - private void paintFoldingTree(Graphics2D g) { - Rectangle clip = g.getClipBounds(); - + private void doPaintFoldingTree(Graphics2D g, Rectangle clip, int firstVisibleOffset, int lastVisibleOffset) { int anchorX = getFoldingAreaOffset(); int width = getFoldingAnchorWidth(); FoldRegion[] visibleFoldRegions = ((FoldingModelImpl)myEditor.getFoldingModel()).fetchVisible(); - int firstVisibleOffset = - myEditor.logicalPositionToOffset(myEditor.xyToLogicalPosition(new Point(0, clip.y - myEditor.getLineHeight()))); - int lastVisibleOffset = - myEditor.logicalPositionToOffset(myEditor.xyToLogicalPosition(new Point(0, clip.y + clip.height + myEditor.getLineHeight()))); - for (FoldRegion visibleFoldRegion : visibleFoldRegions) { if (!visibleFoldRegion.isValid()) continue; if (visibleFoldRegion.getStartOffset() > lastVisibleOffset) continue; @@ -682,8 +670,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse } } - private void paintFoldingBackground(Graphics g) { - Rectangle clip = g.getClipBounds(); + private void paintFoldingBackground(Graphics g, Rectangle clip, int firstVisibleOffset, int lastVisibleOffset) { int lineX = getWhitespaceSeparatorOffset(); paintBackground(g, clip, getFoldingAreaOffset(), getFoldingAreaWidth()); @@ -692,12 +679,11 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse paintCaretRowBackground(g, lineX, getFoldingAnchorWidth()); - paintFoldingBoxBackground((Graphics2D)g); + doPaintFoldingBoxBackground((Graphics2D)g, clip, firstVisibleOffset, lastVisibleOffset); } - private void paintFoldingBoxBackground(Graphics2D g) { + private void doPaintFoldingBoxBackground(Graphics2D g, Rectangle clip, int firstVisibleOffset, int lastVisibleOffset) { if (!isFoldingOutlineShown()) return; - Rectangle clip = g.getClipBounds(); UIUtil.drawVDottedLine(g, getWhitespaceSeparatorOffset(), clip.y, clip.y + clip.height, null, getOutlineColor(false)); @@ -706,11 +692,6 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse FoldRegion[] visibleFoldRegions = ((FoldingModelImpl)myEditor.getFoldingModel()).fetchVisible(); - int firstVisibleOffset = myEditor.logicalPositionToOffset( - myEditor.xyToLogicalPosition(new Point(0, clip.y - myEditor.getLineHeight()))); - int lastVisibleOffset = myEditor.logicalPositionToOffset( - myEditor.xyToLogicalPosition(new Point(0, clip.y + clip.height + myEditor.getLineHeight()))); - if (myActiveFoldRegion != null) { drawFoldingLines(myActiveFoldRegion, clip, width, anchorX, g); } @@ -898,7 +879,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse public boolean isFoldingOutlineShown() { return myEditor.getSettings().isFoldingOutlineShown() && - ((FoldingModelEx)myEditor.getFoldingModel()).isFoldingEnabled(); + myEditor.getFoldingModel().isFoldingEnabled(); } public int getLineNumberAreaWidth() { @@ -1040,17 +1021,15 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse } } - Balloon.Position ballPosition = Balloon.Position.atRight; if (toolTip != null && toolTip.length() != 0) { - LogicalPosition pos = myEditor.xyToLogicalPosition(new Point(0, (int)e.getY())); - int line = pos.line; - final Ref t = new Ref(e.getPoint()); - ArrayList row = myLineToGutterRenderers.get(pos.line); + int line = myEditor.yPositionToLogicalLineNumber(e.getY()); + ArrayList row = myLineToGutterRenderers.get(line); + Balloon.Position ballPosition = Balloon.Position.atRight; if (row != null) { final TreeMap xPos = new TreeMap(); - final int[] currentPos = new int[] {0}; - processIconsRow(pos.line, row, new LineGutterIconRendererProcessor() { + final int[] currentPos = {0}; + processIconsRow(line, row, new LineGutterIconRendererProcessor() { @Override public void process(int x, int y, GutterIconRenderer r) { xPos.put(x, r); @@ -1062,8 +1041,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse } }); - ArrayList xx = new ArrayList(); - xx.addAll(xPos.keySet()); + List xx = new ArrayList(xPos.keySet()); int posIndex = xx.indexOf(currentPos[0]); if (xPos.size() > 1 && posIndex == 0) { ballPosition = Balloon.Position.below; @@ -1108,7 +1086,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse } private int getLineNumAtPoint(final Point clickPoint) { - return myEditor.xyToLogicalPosition(new Point(0, clickPoint.y)).line; + return myEditor.yPositionToLogicalLineNumber(clickPoint.y); } @Nullable @@ -1168,39 +1146,39 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse } private ActiveGutterRenderer getActiveRendererByMouseEvent(final MouseEvent e) { - final ActiveGutterRenderer[] gutterRenderer = {null}; - if (findFoldingAnchorAt(e.getX(), e.getY()) == null) { - if (!e.isConsumed() && - - e.getX() <= getWhitespaceSeparatorOffset()) { - Rectangle clip = myEditor.getScrollingModel().getVisibleArea(); - int firstVisibleOffset = myEditor.logicalPositionToOffset( - myEditor.xyToLogicalPosition(new Point(0, clip.y - myEditor.getLineHeight()))); - int lastVisibleOffset = myEditor.logicalPositionToOffset( - myEditor.xyToLogicalPosition(new Point(0, clip.y + clip.height + myEditor.getLineHeight()))); - - processRangeHighlighters(new RangeHighlighterProcessor() { - public void process(RangeHighlighter highlighter) { - if (gutterRenderer[0] != null) return; - Rectangle rectangle = getLineRendererRectangle(highlighter); - if (rectangle == null) return; - - int startY = rectangle.y; - int endY = startY + rectangle.height; - if (startY == endY) { - endY += myEditor.getLineHeight(); - } - - if (startY < e.getY() && e.getY() <= endY) { - final LineMarkerRenderer renderer = highlighter.getLineMarkerRenderer(); - if (renderer instanceof ActiveGutterRenderer && ((ActiveGutterRenderer)renderer).canDoAction(e)) { - gutterRenderer[0] = (ActiveGutterRenderer)renderer; - } - } - } - }, firstVisibleOffset, lastVisibleOffset); - } + if (findFoldingAnchorAt(e.getX(), e.getY()) != null) { + return null; } + if (e.isConsumed() || e.getX() > getWhitespaceSeparatorOffset()) { + return null; + } + final ActiveGutterRenderer[] gutterRenderer = {null}; + Rectangle clip = myEditor.getScrollingModel().getVisibleArea(); + int firstVisibleOffset = myEditor.logicalPositionToOffset( + myEditor.xyToLogicalPosition(new Point(0, clip.y - myEditor.getLineHeight()))); + int lastVisibleOffset = myEditor.logicalPositionToOffset( + myEditor.xyToLogicalPosition(new Point(0, clip.y + clip.height + myEditor.getLineHeight()))); + + processRangeHighlighters(new RangeHighlighterProcessor() { + public void process(RangeHighlighter highlighter) { + if (gutterRenderer[0] != null) return; + Rectangle rectangle = getLineRendererRectangle(highlighter); + if (rectangle == null) return; + + int startY = rectangle.y; + int endY = startY + rectangle.height; + if (startY == endY) { + endY += myEditor.getLineHeight(); + } + + if (startY < e.getY() && e.getY() <= endY) { + final LineMarkerRenderer renderer = highlighter.getLineMarkerRenderer(); + if (renderer instanceof ActiveGutterRenderer && ((ActiveGutterRenderer)renderer).canDoAction(e)) { + gutterRenderer[0] = (ActiveGutterRenderer)renderer; + } + } + } + }, firstVisibleOffset, lastVisibleOffset); return gutterRenderer[0]; } @@ -1235,7 +1213,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse actionGroup.add(new CloseAnnotationsAction()); final List addActions = new ArrayList(); final Point p = e.getPoint(); - int line = myEditor.xyToLogicalPosition(new Point(0, (int)p.getY())).line; + int line = myEditor.yPositionToLogicalLineNumber((int)p.getY()); if (line >= myEditor.getDocument().getLineCount()) return; for (TextAnnotationGutterProvider gutterProvider : myTextAnnotationGutters) { @@ -1284,7 +1262,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse @Nullable private GutterIconRenderer getGutterRenderer(final Point p) { final int ex = convertX((int)p.getX()); - int line = myEditor.xyToLogicalPosition(new Point(0, (int)p.getY())).line; + int line = myEditor.yPositionToLogicalLineNumber((int)p.getY()); if (line >= myEditor.getDocument().getLineCount()) return null; int startOffset = myEditor.getDocument().getLineStartOffset(line); @@ -1406,7 +1384,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse if (contains(gutterPoint)){ final Point editorPoint = new Point(screenPoint); SwingUtilities.convertPointFromScreen(editorPoint, myEditor.getContentComponent()); - int line = myEditor.xyToLogicalPosition(new Point(0, (int)editorPoint.getY())).line; + int line = myEditor.yPositionToLogicalLineNumber((int)editorPoint.getY()); final Cursor cursor = myGutterDraggableObject.getCursor(line); context.setCursor(cursor); return; @@ -1429,7 +1407,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse if (myGutterDraggableObject != null) { int dropAction = e.getDropAction(); if ((dropAction & DnDConstants.ACTION_MOVE) != 0) { - int line = myEditor.xyToLogicalPosition(new Point(0, (int)e.getLocation().getY())).line; + int line = myEditor.yPositionToLogicalLineNumber((int)e.getLocation().getY()); e.dropComplete(myGutterDraggableObject.copy(line)); return; } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java index 67d4cd713ea5..cb885ea6cb35 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java @@ -843,6 +843,12 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi return y / getLineHeight(); } + public int yPositionToLogicalLineNumber(int y) { + int line = yPositionToVisibleLineNumber(y); + LogicalPosition logicalPosition = visualToLogicalPosition(new VisualPosition(line, 0)); + return logicalPosition.line; + } + @NotNull public VisualPosition xyToVisualPosition(@NotNull Point p) { int line = yPositionToVisibleLineNumber(p.y); @@ -960,6 +966,10 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi if (charWidth < 0) { charWidth = EditorUtil.charWidth(c, fontType, this); } + + if (charWidth <= 0) { + charWidth = spaceSize; + } if (x >= px && c == '\t' && !onSoftWrapDrawing) { if (mySettings.isCaretInsideTabs()) { @@ -975,8 +985,9 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi if ((x - px) * 2 < charWidth) column++; } else { - column += (px - x) / spaceSize; - if ((px - x) * 2 >= spaceSize) { + int diff = px - x; + column += diff / spaceSize; + if ((diff % spaceSize) * 2 >= spaceSize) { column++; } } @@ -1069,13 +1080,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi @NotNull public LogicalPosition xyToLogicalPosition(@NotNull Point p) { - final Point pp; - if (p.x >= 0 && p.y >= 0) { - pp = p; - } - else { - pp = new Point(Math.max(p.x, 0), Math.max(p.y, 0)); - } + Point pp = p.x >= 0 && p.y >= 0 ? p : new Point(Math.max(p.x, 0), Math.max(p.y, 0)); return visualToLogicalPosition(xyToVisualPosition(pp)); } @@ -1598,6 +1603,9 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi if (!getFoldingModel().isOffsetCollapsed(startOffset)) { if (visibleStartLine >= startLineNumber && visibleStartLine <= endLineNumber) { int logStartLine = offsetToLogicalPosition(startOffset).line; + if (logStartLine >= myDocument.getLineCount()) { + return; + } LogicalPosition logPosition = offsetToLogicalPosition(myDocument.getLineEndOffset(logStartLine)); Point end = logicalPositionToXY(logPosition); int charWidth = EditorUtil.getSpaceWidth(Font.PLAIN, this); @@ -5199,7 +5207,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi protected void processMouseWheelEvent(MouseWheelEvent e) { if (mySettings.isWheelFontChangeEnabled()) { if (isChangeFontSize(e)) { - setFontSize(myScheme.getEditorFontSize() + e.getWheelRotation()); + setFontSize(myScheme.getEditorFontSize() - e.getWheelRotation()); return; } } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java index 90cd4726f1d1..35cf216da303 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java @@ -762,6 +762,7 @@ public class EditorMarkupModelImpl extends MarkupModelImpl implements EditorMark else { endY = myEditorScrollbarTop + (int)((float)endLineNumber / lineCount * myEditorTargetHeight); } + if (endY < startY) endY = startY; } return new ProperTextRange(startY, endY); } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EmptyMarkupModel.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EmptyMarkupModel.java index eb39a4684032..bfd875561efd 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EmptyMarkupModel.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EmptyMarkupModel.java @@ -50,7 +50,7 @@ public class EmptyMarkupModel implements MarkupModelEx { int endOffset, int layer, TextAttributes textAttributes, - HighlighterTargetArea targetArea, + @NotNull HighlighterTargetArea targetArea, boolean isPersistent, Consumer changeAttributesAction) { throw new ProcessCanceledException(); @@ -66,7 +66,7 @@ public class EmptyMarkupModel implements MarkupModelEx { throw new ProcessCanceledException(); } - public void removeHighlighter(RangeHighlighter rangeHighlighter) { + public void removeHighlighter(@NotNull RangeHighlighter rangeHighlighter) { } public void removeAllHighlighters() { diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/IntervalTreeImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/IntervalTreeImpl.java index 85349fc9ab64..02d90e64dc35 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/IntervalTreeImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/IntervalTreeImpl.java @@ -231,7 +231,7 @@ public abstract class IntervalTreeImpl extends RedBla return processOverlapping(root.getRight(), offset, processor, modCountBefore, delta); } - private void insert(MyNode newNode) { + protected void insert(MyNode newNode) { T key = newNode.key; if (root == null) { root = newNode; diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/MarkupModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/MarkupModelImpl.java index 75cde4d3ef2d..193990d041be 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/MarkupModelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/MarkupModelImpl.java @@ -111,12 +111,12 @@ public class MarkupModelImpl extends UserDataHolderBase implements MarkupModelEx int endOffset, int layer, TextAttributes textAttributes, - HighlighterTargetArea targetArea, + @NotNull HighlighterTargetArea targetArea, boolean isPersistent, @Nullable Consumer changeAttributesAction) { RangeHighlighterEx highlighter = isPersistent - ? new PersistentRangeHighlighterImpl(this, startOffset, layer, targetArea, textAttributes) - : new RangeHighlighterImpl(this, startOffset, endOffset, layer, targetArea, textAttributes); + ? new PersistentRangeHighlighterImpl(this, startOffset, layer, targetArea, textAttributes) + : new RangeHighlighterImpl(this, startOffset, endOffset, layer, targetArea, textAttributes); RangeMarkerImpl marker = (RangeMarkerImpl)highlighter; marker.registerInDocument(); @@ -145,9 +145,7 @@ public class MarkupModelImpl extends UserDataHolderBase implements MarkupModelEx } void addRangeHighlighter(RangeHighlighterEx marker) { - marker.setValid(true); - ((RangeMarkerImpl)marker).myNode = (IntervalTreeImpl.MyNode)myHighlighterTree.add(marker); - myHighlighterTree.checkMax(true); + myHighlighterTree.add(marker); } @NotNull @@ -159,7 +157,7 @@ public class MarkupModelImpl extends UserDataHolderBase implements MarkupModelEx return addRangeHighlighterAndChangeAttributes(startOffset, endOffset, layer, textAttributes, targetArea, false, null); } - public void removeHighlighter(RangeHighlighter segmentHighlighter) { + public void removeHighlighter(@NotNull RangeHighlighter segmentHighlighter) { myCachedHighlighters = null; if (!segmentHighlighter.isValid()) return; diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java index e8df2f762632..073b3fdcd7ce 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java @@ -89,6 +89,27 @@ public class RangeMarkerTree extends IntervalTreeImpl= myCache.size() || myCache.get(startIndex).startOffset > endOffset) { + return; + } } int endIndex = endCacheEntryIndex; if (endIndex < 0) { diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/MappingUtil.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/MappingUtil.java index be229c854237..4491db6127df 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/MappingUtil.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/MappingUtil.java @@ -45,12 +45,7 @@ public class MappingUtil { */ public static int getCacheEntryIndexForOffset(int offset, Document document, List cache) { if (offset >= document.getTextLength() && (cache.isEmpty() || cache.get(cache.size() - 1).endOffset < offset)) { - if (cache.isEmpty()) { - return -1; - } - else { - return cache.size() - 1; - } + return -(cache.size() + 1); } int start = 0; diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java index 42ae65b17331..1917e94572d0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java @@ -1025,7 +1025,7 @@ public class SoftWrapApplianceManager implements FoldingListener, DocumentListen * [{@link #startOffset}; {@link #skipToLineEnd} is set to 'true' otherwise */ public void tryToShiftToNextLine() { - for (int i = startOffset; i < endOffset; i++, currentPosition.offset++) { + for (int i = currentPosition.offset; i < endOffset; i++, currentPosition.offset++) { char c = text.charAt(i); currentPosition.offset = i; if (c == '\n') { diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/textarea/TextComponentCaretModel.java b/platform/platform-impl/src/com/intellij/openapi/editor/textarea/TextComponentCaretModel.java index 79439578f2ad..51516e563ba0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/textarea/TextComponentCaretModel.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/textarea/TextComponentCaretModel.java @@ -20,6 +20,7 @@ import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.VisualPosition; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.editor.event.CaretListener; +import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.text.BadLocationException; @@ -43,11 +44,11 @@ public class TextComponentCaretModel implements CaretModel { throw new UnsupportedOperationException("Not implemented"); } - public void moveToLogicalPosition(final LogicalPosition pos) { + public void moveToLogicalPosition(@NotNull final LogicalPosition pos) { moveToOffset(myEditor.logicalPositionToOffset(pos), false); } - public void moveToVisualPosition(final VisualPosition pos) { + public void moveToVisualPosition(@NotNull final VisualPosition pos) { moveToLogicalPosition(myEditor.visualToLogicalPosition(pos)); } @@ -60,6 +61,7 @@ public class TextComponentCaretModel implements CaretModel { myTextComponent.setCaretPosition(Math.min(offset, myTextComponent.getText().length())); } + @NotNull public LogicalPosition getLogicalPosition() { int caretPos = myTextComponent.getCaretPosition(); int line; @@ -81,6 +83,7 @@ public class TextComponentCaretModel implements CaretModel { return new LogicalPosition(line, caretPos - lineStart); } + @NotNull public VisualPosition getVisualPosition() { LogicalPosition pos = getLogicalPosition(); return new VisualPosition(pos.line, pos.column); @@ -90,11 +93,11 @@ public class TextComponentCaretModel implements CaretModel { return myTextComponent.getCaretPosition(); } - public void addCaretListener(final CaretListener listener) { + public void addCaretListener(@NotNull final CaretListener listener) { throw new UnsupportedOperationException("Not implemented"); } - public void removeCaretListener(final CaretListener listener) { + public void removeCaretListener(@NotNull final CaretListener listener) { throw new UnsupportedOperationException("Not implemented"); } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/ex/FileEditorManagerEx.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/ex/FileEditorManagerEx.java index 2db93fc7644b..3dfccb20c741 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/ex/FileEditorManagerEx.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/ex/FileEditorManagerEx.java @@ -123,10 +123,18 @@ public abstract class FileEditorManagerEx extends FileEditorManager { @NotNull public FileEditor[] openFile(@NotNull final VirtualFile file, final boolean focusEditor) { - return openFileWithProviders(file, focusEditor).getFirst (); + return openFileWithProviders(file, focusEditor, false).getFirst (); } - @NotNull public abstract Pair openFileWithProviders(@NotNull VirtualFile file, boolean focusEditor); + @NotNull + @Override + public FileEditor[] openFile(@NotNull VirtualFile file, boolean focusEditor, boolean searchForSplitter) { + return openFileWithProviders(file, focusEditor, searchForSplitter).getFirst(); + } + + @NotNull public abstract Pair openFileWithProviders(@NotNull VirtualFile file, + boolean focusEditor, + boolean searchForSplitter); public abstract boolean isChanged(@NotNull EditorComposite editor); diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java index f453068d29ab..f25d4eb9262e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerImpl.java @@ -547,18 +547,31 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Projec //-------------------------------------- Open File ---------------------------------------- - @NotNull public Pair openFileWithProviders(@NotNull final VirtualFile file, final boolean focusEditor) { + @NotNull public Pair openFileWithProviders(@NotNull final VirtualFile file, + final boolean focusEditor, + boolean searchForSplitter) { if (!file.isValid()) { throw new IllegalArgumentException("file is not valid: " + file); } assertDispatchThread(); - EditorsSplitters splitters = getSplitters(); - EditorWindow wndToOpenIn = splitters.getCurrentWindow(); + EditorWindow wndToOpenIn = null; + if (searchForSplitter) { + for (EditorsSplitters splitters : getAllSplitters()) { + final EditorWindow window = splitters.getCurrentWindow(); + if (window == null) continue; + + if (window.isFileOpen(file)) { + wndToOpenIn = window; + break; + } + } + } else { + wndToOpenIn = getSplitters().getCurrentWindow(); + } if (wndToOpenIn == null) { - wndToOpenIn = splitters.getOrCreateCurrentWindow(file); + wndToOpenIn = getSplitters().getOrCreateCurrentWindow(file); } - return openFileImpl2(wndToOpenIn, file, focusEditor); } @@ -728,7 +741,7 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Projec if (!ApplicationManagerEx.getApplicationEx().isUnitTestMode()) { if (focusEditor) { //myFirstIsActive = myTabbedContainer1.equals(tabbedContainer); - window.setAsCurrentWindow(false); + window.setAsCurrentWindow(true); ToolWindowManager.getInstance(myProject).activateEditorComponent(); } } @@ -1018,10 +1031,13 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Projec public FileEditor[] getAllEditors() { assertReadAccess(); final ArrayList result = new ArrayList(); - final EditorWithProviderComposite[] editorsComposites = getSplitters().getEditorsComposites(); - for (EditorWithProviderComposite editorsComposite : editorsComposites) { - final FileEditor[] editors = editorsComposite.getEditors(); - ContainerUtil.addAll(result, editors); + final Set allSplitters = getAllSplitters(); + for (EditorsSplitters splitter : allSplitters) { + final EditorWithProviderComposite[] editorsComposites = splitter.getEditorsComposites(); + for (EditorWithProviderComposite editorsComposite : editorsComposites) { + final FileEditor[] editors = editorsComposite.getEditors(); + ContainerUtil.addAll(result, editors); + } } return result.toArray(new FileEditor[result.size()]); } @@ -1168,15 +1184,17 @@ public class FileEditorManagerImpl extends FileEditorManagerEx implements Projec } private EditorWithProviderComposite getEditorComposite(@NotNull final FileEditor editor) { - final EditorWithProviderComposite[] editorsComposites = getSplitters().getEditorsComposites(); - for (int i = editorsComposites.length - 1; i >= 0; i--) { - final EditorWithProviderComposite composite = editorsComposites[i]; - final FileEditor[] editors = composite.getEditors(); - for (int j = editors.length - 1; j >= 0; j--) { - final FileEditor _editor = editors[j]; - LOG.assertTrue(_editor != null); - if (editor.equals(_editor)) { - return composite; + for (EditorsSplitters splitters : getAllSplitters()) { + final EditorWithProviderComposite[] editorsComposites = splitters.getEditorsComposites(); + for (int i = editorsComposites.length - 1; i >= 0; i--) { + final EditorWithProviderComposite composite = editorsComposites[i]; + final FileEditor[] editors = composite.getEditors(); + for (int j = editors.length - 1; j >= 0; j--) { + final FileEditor _editor = editors[j]; + LOG.assertTrue(_editor != null); + if (editor.equals(_editor)) { + return composite; + } } } } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java index 52011d1180bf..f4b1eb5a862b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java @@ -443,7 +443,7 @@ public class IdeDocumentHistoryImpl extends IdeDocumentHistory implements Projec private void gotoPlaceInfo(@NotNull PlaceInfo info) { // TODO: Msk final boolean wasActive = myToolWindowManager.isEditorComponentActive(); - final Pair editorsWithProviders = myEditorManager.openFileWithProviders(info.getFile(), wasActive); + final Pair editorsWithProviders = myEditorManager.openFileWithProviders(info.getFile(), wasActive, false); final FileEditor [] editors = editorsWithProviders.getFirst(); final FileEditorProvider[] providers = editorsWithProviders.getSecond(); for (int i = 0; i < editors.length; i++) { diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java index 327014e8e3e8..d5d56795c9e6 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java @@ -55,7 +55,7 @@ import java.util.regex.Pattern; */ public class FileTypeManagerImpl extends FileTypeManagerEx implements NamedJDOMExternalizable, ExportableApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl"); - private static final int VERSION = 7; + private static final int VERSION = 8; private final Set myDefaultTypes = new THashSet(); private final ArrayList mySpecialFileTypes = new ArrayList(); @@ -520,9 +520,14 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements NamedJDOME addIgnore("_svn"); } - if (savedVersion < VERSION) { + if (savedVersion < 7) { addIgnore(".hg"); } + + if (savedVersion < VERSION) { + addIgnore("*.lib"); + addIgnore("*~"); + } } private void readGlobalMappings(final Element e) { diff --git a/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurablesGroupBase.java b/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurablesGroupBase.java index d42f87f72f6b..6a87cc4a1589 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurablesGroupBase.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurablesGroupBase.java @@ -31,17 +31,20 @@ public abstract class ConfigurablesGroupBase implements ConfigurableGroup { private Configurable[] myChildren; private ComponentManager myComponentManager; private final ExtensionPointName myConfigurablesExtensionPoint; + private final boolean myLoadComponents; - protected ConfigurablesGroupBase(ComponentManager componentManager, final ExtensionPointName configurablesExtensionPoint) { + protected ConfigurablesGroupBase(ComponentManager componentManager, final ExtensionPointName configurablesExtensionPoint, + boolean loadComponents) { myComponentManager = componentManager; myConfigurablesExtensionPoint = configurablesExtensionPoint; + myLoadComponents = loadComponents; } @Override public Configurable[] getConfigurables() { if (myChildren == null) { final ConfigurableEP[] extensions = myComponentManager.getExtensions(myConfigurablesExtensionPoint); - Configurable[] components = myComponentManager.getComponents(Configurable.class); + Configurable[] components = myLoadComponents ? myComponentManager.getComponents(Configurable.class) : new Configurable[0]; List result = ConfigurableExtensionPointUtil.buildConfigurablesList(extensions, components, getConfigurableFilter()); myChildren = result.toArray(new Configurable[result.size()]); diff --git a/platform/platform-impl/src/com/intellij/openapi/options/ex/IdeConfigurablesGroup.java b/platform/platform-impl/src/com/intellij/openapi/options/ex/IdeConfigurablesGroup.java index 4ee03b08bcf1..c12db83a0d16 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/ex/IdeConfigurablesGroup.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/ex/IdeConfigurablesGroup.java @@ -28,7 +28,7 @@ import com.intellij.openapi.options.OptionsBundle; */ public class IdeConfigurablesGroup extends ConfigurablesGroupBase implements ConfigurableGroup { public IdeConfigurablesGroup() { - super(ApplicationManager.getApplication(), ConfigurableExtensionPointUtil.APPLICATION_CONFIGURABLES); + super(ApplicationManager.getApplication(), ConfigurableExtensionPointUtil.APPLICATION_CONFIGURABLES, true); } public String getDisplayName() { diff --git a/platform/platform-impl/src/com/intellij/openapi/options/ex/ProjectConfigurablesGroup.java b/platform/platform-impl/src/com/intellij/openapi/options/ex/ProjectConfigurablesGroup.java index 910bf991e967..f27722baad5d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/ex/ProjectConfigurablesGroup.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/ex/ProjectConfigurablesGroup.java @@ -28,7 +28,7 @@ public class ProjectConfigurablesGroup extends ConfigurablesGroupBase implements private final Project myProject; public ProjectConfigurablesGroup(Project project) { - super(project, ConfigurableExtensionPointUtil.PROJECT_CONFIGURABLES); + super(project, ConfigurableExtensionPointUtil.PROJECT_CONFIGURABLES, true); myProject = project; } diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java b/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java index 4c92d2f5e44b..2a20434a26a3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java @@ -279,6 +279,11 @@ public class FrameWrapper implements Disposable, DataProvider { setGlassPane(new IdeGlassPaneImpl(getRootPane())); } + @Override + public JComponent getComponent() { + return getRootPane(); + } + @Override public StatusBar getStatusBar() { return myStatusBar != null ? myStatusBar : myParent.getStatusBar(); diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateSettingsConfigurable.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateSettingsConfigurable.java index f50cd83d3da2..9874a4cf0eac 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateSettingsConfigurable.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateSettingsConfigurable.java @@ -84,6 +84,7 @@ public class UpdateSettingsConfigurable extends BaseConfigurable implements Sear } public boolean isModified() { + if (myUpdatesSettingsPanel == null) return false; UpdateSettings settings = UpdateSettings.getInstance(); if (!settings.myPluginHosts.equals(myUpdatesSettingsPanel.getPluginsHosts())) return true; return settings.CHECK_NEEDED != myUpdatesSettingsPanel.myCbCheckForUpdates.isSelected(); diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java index 471f96894c78..71ed8bef0acf 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/impl/VirtualDirectoryImpl.java @@ -97,6 +97,7 @@ public class VirtualDirectoryImpl extends VirtualFileSystemEntry { final NewVirtualFileSystem delegate = getFileSystem(); VirtualFile fake = new FakeVirtualFile(this, name); name = delegate.getCanonicallyCasedName(fake); + if (name.length() == 0) return null; } synchronized (this) { diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java index 312ba258a2f9..45f859f031c5 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java @@ -247,7 +247,15 @@ public class FSRecords implements Forceable { private static void invalidateIndex() { LOG.info("Marking VFS as corrupted"); - FileUtil.createIfDoesntExist(new File(PathManager.getIndexRoot(), "corruption.marker")); + final File indexRoot = PathManager.getIndexRoot(); + if (indexRoot.exists()) { + final String[] children = indexRoot.list(); + if (children != null && children.length > 0) { + // create index corruption marker only if index directory exists and is non-empty + // It is incorrect to consider non-existing indices "corrupted" + FileUtil.createIfDoesntExist(new File(PathManager.getIndexRoot(), "corruption.marker")); + } + } } private static File basePath() { diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFS.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFS.java index e7f521c1ef18..5489c0407ccb 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFS.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFS.java @@ -63,6 +63,7 @@ public class PersistentFS extends ManagingFS implements ApplicationComponent { private final MessageBus myEventsBus; private final Map myRoots = new HashMap(); + private NewVirtualFile myFakeRoot; private final Object INPUT_LOCK = new Object(); /** * always in range [0, PersistentFS.FILE_LENGTH_TO_CACHE_THRESHOLD] @@ -635,6 +636,9 @@ public class PersistentFS extends ManagingFS implements ApplicationComponent { synchronized (LOCK) { final String rootUrl = fs.getProtocol() + "://" + basePath; NewVirtualFile root = myRoots.get(rootUrl); + if (root == null && basePath.length() == 0) { + root = myFakeRoot; + } if (root == null) { try { final int rootId = myRecords.findRootRecord(rootUrl); @@ -661,6 +665,9 @@ public class PersistentFS extends ManagingFS implements ApplicationComponent { if (basePath.length() > 0) { myRoots.put(rootUrl, root); } + else { + myFakeRoot = root; + } } return root; diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java index 9a8f59fe02e8..ab65b36a2462 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java @@ -79,10 +79,7 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { } } }; - private boolean myFlushWasDelayedToFixFocusByDefaultRequest; - - private FocusCommand myRestoreFocusOnFlushCmd; - private ActionCallback myRestoreFocusOnFlushCallback; + private boolean myFlushWasDelayedToFixFocus; private boolean canFlushIdleRequests() { return isFocusTransferReady() && !isIdleQueueEmpty(); @@ -176,12 +173,6 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { if (forced) { myForcedFocusRequestsAlarm.cancelAllRequests(); setLastEffectiveForcedRequest(command); - - if (myRestoreFocusOnFlushCmd != null) { - rejectCommand(myRestoreFocusOnFlushCmd, myRestoreFocusOnFlushCallback, false); - myRestoreFocusOnFlushCmd = null; - myRestoreFocusOnFlushCallback = null; - } } SwingUtilities.invokeLater(new Runnable() { @@ -230,7 +221,7 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { }).notify(focusTimeout); } else { - rejectCommand(command, result, false); + rejectCommand(command, result); } } }); @@ -238,7 +229,7 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { private boolean checkForRejectOrByPass(final FocusCommand cmd, final boolean forced, final ActionCallback result) { if (cmd.isExpired()) { - rejectCommand(cmd, result, false); + rejectCommand(cmd, result); return true; } @@ -250,14 +241,14 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { result.setDone(); } else { - rejectCommand(cmd, result, true); + rejectCommand(cmd, result); } return true; } if (lastRequest != null && lastRequest.dominatesOver(cmd)) { - rejectCommand(cmd, result, false); + rejectCommand(cmd, result); return true; } @@ -432,28 +423,15 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { if (isPendingKeyEventsRedispatched()) { - boolean focusOk = getFocusOwner() != null; + boolean focusOk = getFocusOwner() != null || myFlushWasDelayedToFixFocus; + if (!focusOk) { + IdeEventQueue.getInstance().fixStickyFocusedComponents(null); + myFlushWasDelayedToFixFocus = true; + } - if (!focusOk && myRestoreFocusOnFlushCmd != null) { - FocusCommand cmd = myRestoreFocusOnFlushCmd; - ActionCallback cb = myRestoreFocusOnFlushCallback; - - myRestoreFocusOnFlushCmd = null; - myRestoreFocusOnFlushCallback = null; - - requestFocus(cmd, true).notify(cb); - } else { - boolean noNeedToFixFocus = focusOk || myFlushWasDelayedToFixFocusByDefaultRequest; - - if (!noNeedToFixFocus) { - IdeEventQueue.getInstance().fixStickyFocusedComponents(null); - myFlushWasDelayedToFixFocusByDefaultRequest = true; - } - - if (canFlushIdleRequests() && getFlushingIdleRequests() <= 1 && (noNeedToFixFocus || !myFlushWasDelayedToFixFocusByDefaultRequest)) { - myFlushWasDelayedToFixFocusByDefaultRequest = false; - flushNow(); - } + if (canFlushIdleRequests() && getFlushingIdleRequests() <= 1 && (focusOk || !myFlushWasDelayedToFixFocus)) { + myFlushWasDelayedToFixFocus = false; + flushNow(); } } } @@ -636,6 +614,12 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { } } + @Override + public Component getLastFocusedFor(IdeFrame frame) { + WeakReference ref = myLastFocused.get(frame); + return ref != null ? ref.get() : null; + } + private static class FurtherRequestor implements FocusRequestor { private final IdeFocusManager myManager; private final Expirable myExpirable; @@ -676,25 +660,15 @@ public class FocusManagerImpl extends IdeFocusManager implements Disposable { } private void forceFinishFocusSettledown(FocusCommand cmd, ActionCallback cmdCallback) { - rejectCommand(cmd, cmdCallback, false); + rejectCommand(cmd, cmdCallback); } - private void rejectCommand(FocusCommand cmd, ActionCallback callback, boolean canBeUseToFixNullFocusOnFlush) { - resetCommand(cmd, !canBeUseToFixNullFocusOnFlush); + private void rejectCommand(FocusCommand cmd, ActionCallback callback) { + resetCommand(cmd, true); resetUnforcedCommand(cmd); - - if (canBeUseToFixNullFocusOnFlush) { - if (myRestoreFocusOnFlushCmd != null) { - rejectCommand(myRestoreFocusOnFlushCmd, myRestoreFocusOnFlushCallback, false); - } - - myRestoreFocusOnFlushCmd = cmd; - myRestoreFocusOnFlushCallback = callback; - } else { - callback.setRejected(); - } + callback.setRejected(); } private class AppListener extends ApplicationAdapter { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerHeadless.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerHeadless.java index ded95f259b16..088c0f4a291a 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerHeadless.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerHeadless.java @@ -21,6 +21,7 @@ import com.intellij.openapi.util.Expirable; import com.intellij.openapi.wm.FocusCommand; import com.intellij.openapi.wm.FocusRequestor; import com.intellij.openapi.wm.IdeFocusManager; +import com.intellij.openapi.wm.IdeFrame; import org.jetbrains.annotations.NotNull; import javax.swing.*; @@ -98,4 +99,9 @@ public class IdeFocusManagerHeadless extends IdeFocusManager { public void runOnOwnContext(DataContext context, Runnable runnable) { runnable.run(); } + + @Override + public Component getLastFocusedFor(IdeFrame frame) { + return null; + } } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerImpl.java index 1d97067c18a7..3275fa70e804 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFocusManagerImpl.java @@ -21,6 +21,7 @@ import com.intellij.openapi.util.Expirable; import com.intellij.openapi.wm.FocusCommand; import com.intellij.openapi.wm.FocusRequestor; import com.intellij.openapi.wm.IdeFocusManager; +import com.intellij.openapi.wm.IdeFrame; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -97,6 +98,11 @@ public class IdeFocusManagerImpl extends IdeFocusManager { getGlobalInstance().runOnOwnContext(context, runnable); } + @Override + public Component getLastFocusedFor(IdeFrame frame) { + return getGlobalInstance().getLastFocusedFor(frame); + } + public boolean isFocusBeingTransferred() { return getGlobalInstance().isFocusBeingTransferred(); } diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java index ed0f7c5f5cd0..55e7c47ffecd 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java @@ -101,6 +101,11 @@ public class IdeFrameImpl extends JFrame implements IdeFrame, DataProvider { } + @Override + public JComponent getComponent() { + return getRootPane(); + } + private static boolean isThereActiveFrame() { Frame[] all = Frame.getFrames(); for (Frame each : all) { diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java index 85a0a8aeb1f4..3f1759a977ec 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/MemoryUsagePanel.java @@ -16,10 +16,6 @@ package com.intellij.openapi.wm.impl.status; import com.intellij.concurrency.JobScheduler; -import com.intellij.notification.Notification; -import com.intellij.notification.NotificationDisplayType; -import com.intellij.notification.NotificationType; -import com.intellij.notification.Notifications; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.wm.CustomStatusBarWidget; import com.intellij.openapi.wm.StatusBar; @@ -74,22 +70,7 @@ public class MemoryUsagePanel extends JButton implements CustomStatusBarWidget { myFuture = null; } - - private static final int CRITICAL_XMX_THRESHOLD_MB = 700; - private static final int CRITICAL_XMX_THRESHOLD = CRITICAL_XMX_THRESHOLD_MB /*Mb*/ * 1024 /*Kb*/ * 1024 /*Bytes*/; - public void install(@NotNull StatusBar statusBar) { - if (SystemInfo.isWindows && SystemInfo.is32Bit) { - final long maxMem = Runtime.getRuntime().maxMemory(); - if (maxMem > CRITICAL_XMX_THRESHOLD) { - final String text = - "Current maximum heap size is set to " + - (maxMem / 1024 / 1024) + " Mb. " + - "On a 32-bit system this may cause OutOfMemory errors. It is recommended to specify heap size not more than " + - CRITICAL_XMX_THRESHOLD_MB + " Mb"; - Notifications.Bus.notify(new Notification("Memory", "Too Large Heap Size", text, NotificationType.WARNING), NotificationDisplayType.STICKY_BALLOON, null); - } - } } @Nullable diff --git a/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java b/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java index 07021bc996ff..8f3850a6dc5b 100644 --- a/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java +++ b/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java @@ -62,6 +62,7 @@ public class FocusTrackback { private WeakReference myRequestor; private boolean mySheduledForRestore; private boolean myWillBeSheduledForRestore; + private boolean myForcedRestore; public FocusTrackback(@NotNull Object requestor, Component parent, boolean mustBeShown) { this(requestor, (parent instanceof Window) ? (Window)parent : SwingUtilities.getWindowAncestor(parent), mustBeShown); @@ -190,7 +191,7 @@ public class FocusTrackback { if (project != null && !project.isDisposed()) { final IdeFocusManager focusManager = IdeFocusManager.getInstance(project); - focusManager.requestFocus(new MyFocusCommand(), false).doWhenProcessed(new Runnable() { + focusManager.requestFocus(new MyFocusCommand(), myForcedRestore).doWhenProcessed(new Runnable() { public void run() { dispose(); } @@ -389,6 +390,10 @@ public class FocusTrackback { return myWillBeSheduledForRestore; } + public void setForcedRestore(boolean forcedRestore) { + myForcedRestore = forcedRestore; + } + public interface Provider { FocusTrackback getFocusTrackback(); } @@ -425,6 +430,9 @@ public class FocusTrackback { Component eachToFocus = getFocusOwner(); FocusTrackback eachTrackback = this; while (true) { + if (eachToFocus == null) { + break; + } if (SwingUtilities.isDescendingFrom(eachToFocus, parent)) return true; if (eachTrackback.getRequestor() instanceof AbstractPopup) { diff --git a/platform/platform-impl/src/com/intellij/ui/LicenseeInfoProvider.java b/platform/platform-impl/src/com/intellij/ui/LicenseeInfoProvider.java index e7264babb14f..bee96727ff6d 100644 --- a/platform/platform-impl/src/com/intellij/ui/LicenseeInfoProvider.java +++ b/platform/platform-impl/src/com/intellij/ui/LicenseeInfoProvider.java @@ -15,7 +15,6 @@ */ package com.intellij.ui; -import com.intellij.openapi.components.ServiceManager; import org.jetbrains.annotations.Nullable; import java.util.Date; @@ -24,8 +23,11 @@ import java.util.Date; * @author yole */ public abstract class LicenseeInfoProvider { + public static LicenseeInfoProvider ourInstance; + + @Nullable public static LicenseeInfoProvider getInstance() { - return ServiceManager.getService(LicenseeInfoProvider.class); + return ourInstance; } public abstract String getLicensedToMessage(); diff --git a/platform/platform-impl/src/com/intellij/ui/ListSpeedSearch.java b/platform/platform-impl/src/com/intellij/ui/ListSpeedSearch.java index 1ba521c4ba22..d3b64b2f9690 100644 --- a/platform/platform-impl/src/com/intellij/ui/ListSpeedSearch.java +++ b/platform/platform-impl/src/com/intellij/ui/ListSpeedSearch.java @@ -16,6 +16,7 @@ package com.intellij.ui; import com.intellij.util.Function; +import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -57,6 +58,6 @@ public class ListSpeedSearch extends SpeedSearchBase { if (myElementTextDelegate != null) { return myElementTextDelegate.fun(element); } - return element.toString(); + return element == null ? null : element.toString(); } } \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/ui/Splash.java b/platform/platform-impl/src/com/intellij/ui/Splash.java index ea69926b9016..80fd99d0b5d1 100644 --- a/platform/platform-impl/src/com/intellij/ui/Splash.java +++ b/platform/platform-impl/src/com/intellij/ui/Splash.java @@ -56,8 +56,10 @@ public class Splash extends JDialog { g.setColor(textColor); LicenseeInfoProvider provider = LicenseeInfoProvider.getInstance(); if (provider != null) { - g.drawString(provider.getLicensedToMessage(), x + 20, y + height - 52); - g.drawString(provider.getLicenseRestrictionsMessage(), x + 20, y + height - 32); + final String licensedToMessage = provider.getLicensedToMessage(); + final String licenseRestrictionsMessage = provider.getLicenseRestrictionsMessage(); + g.drawString(licensedToMessage, x + 20, y + height - 52); + g.drawString(licenseRestrictionsMessage, x + 20, y + height - 32); } return true; } diff --git a/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java b/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java index 3e647c932495..a2fab937501b 100644 --- a/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java +++ b/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java @@ -512,6 +512,7 @@ public class AbstractPopup implements JBPopup { } if (myInStack) { + myFocusTrackback.setForcedRestore(!myOk); myFocusTrackback.restoreFocus(); } diff --git a/platform/platform-impl/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java b/platform/platform-impl/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java index da4287a6dd8f..9a825c0db9ce 100644 --- a/platform/platform-impl/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java +++ b/platform/platform-impl/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java @@ -24,7 +24,7 @@ import gnu.trove.TIntProcedure; import java.awt.*; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; import java.util.List; /** @@ -255,6 +255,47 @@ public class SoftWrapApplianceOnDocumentModificationTest extends AbstractEditorP assertEquals(softWrapsBeforeModification, getSoftWrapModel().getRegisteredSoftWraps()); } + public void testRemoveOfAllSymbolsFromLastLine() throws IOException { + // There was a problem that removing all text from the last document line corrupted soft wraps cache. + String text = + "Line1\n" + + "Long line2 that is expected to be soft-wrapped"; + init(150, text); + + List softWrapsBeforeModification = new ArrayList(getSoftWrapModel().getRegisteredSoftWraps()); + assertTrue(softWrapsBeforeModification.size() > 0); + + int offset = myEditor.getCaretModel().getOffset(); + VisualPosition positionBeforeModification = myEditor.offsetToVisualPosition(offset); + type("\n123"); + myEditor.getSelectionModel().setSelection(offset + 1, myEditor.getDocument().getTextLength()); + delete(); + assertEquals(softWrapsBeforeModification, getSoftWrapModel().getRegisteredSoftWraps()); + assertEquals(positionBeforeModification, myEditor.offsetToVisualPosition(offset)); + } + + public void testTypingBeforeCollapsedFoldRegion() throws IOException { + // We had a problem that soft wraps cache entries that lay after the changed region were considered to be affected by the change. + // This test checks that situation. + String text = + "\n" + + "fold line1\n" + + "fold line2\n" + + "fold line3\n" + + "fold line4\n" + + "normal line1"; + init(150, text); + + int afterFoldOffset = text.indexOf("normal line1"); + addCollapsedFoldRegion(text.indexOf("fold line1") + 2, afterFoldOffset - 1, "..."); + VisualPosition beforeModification = myEditor.offsetToVisualPosition(afterFoldOffset); + + myEditor.getCaretModel().moveToOffset(0); + type('a'); + + assertEquals(beforeModification, myEditor.offsetToVisualPosition(afterFoldOffset + 1)); + } + private static TIntHashSet collectSoftWrapStartOffsets(int documentLine) { TIntHashSet result = new TIntHashSet(); for (SoftWrap softWrap : myEditor.getSoftWrapModel().getSoftWrapsForLine(documentLine)) { diff --git a/platform/platform-resources-en/src/messages/IdeBundle.properties b/platform/platform-resources-en/src/messages/IdeBundle.properties index 481d96ea5b45..94f6c57750c2 100644 --- a/platform/platform-resources-en/src/messages/IdeBundle.properties +++ b/platform/platform-resources-en/src/messages/IdeBundle.properties @@ -1077,3 +1077,19 @@ use.sun.jdk.prompt=Java version is not supported, please use Sun/Oracle JDK rath prompt.goto.inspection.enter.name=Enter inspection name: goto.inspection.action.text=&Run Inspection by Name... label.no.inspections.found=No inspections found + +#Scripting library management +scripting.lib.file.location=Location +scripting.lib.file.type=Type +scripting.lib.select.root=Select library file or directory +scripting.lib.invalid.name=Invalid library name +scripting.lib.attach=&Attach... +scripting.lib.detach=&Detach +scripting.lib.add=&Add... +scripting.lib.edit=&Edit... +scripting.lib.remove=&Remove +scripting.lib.usageScope=Usage Scope +scripting.lib.usageScope.caption=Specify which libraries are used in specific files and/or directories. +scripting.lib.usageScope.tableTitle=Library +scripting.lib.usageScope.override.question=Override library settings for child directories and files? +scripting.lib.usageScope.override.title=Override Library Settings \ No newline at end of file diff --git a/platform/platform-resources-en/src/misc/registry.properties b/platform/platform-resources-en/src/misc/registry.properties index 77c137c2a185..624644a948cf 100644 --- a/platform/platform-resources-en/src/misc/registry.properties +++ b/platform/platform-resources-en/src/misc/registry.properties @@ -106,4 +106,5 @@ jar.build=false keymap.show.alias.actions=false frameworks.download.libraries.server.url=http://pluginsrepo-test:8080 caches.indexerThreadsCount=-1 -vcs.show.history.numbers=true \ No newline at end of file +vcs.show.history.numbers=true +navbar.updateMergeTime=250 \ No newline at end of file diff --git a/platform/platform-resources/src/idea/LangActions.xml b/platform/platform-resources/src/idea/LangActions.xml index 9c08ef8d9014..2f5f09ae5270 100644 --- a/platform/platform-resources/src/idea/LangActions.xml +++ b/platform/platform-resources/src/idea/LangActions.xml @@ -134,7 +134,7 @@ - + @@ -146,7 +146,7 @@ - + @@ -156,7 +156,7 @@ - + diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java index 30828d22d16b..29f104eb3926 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java @@ -73,6 +73,7 @@ import com.intellij.util.indexing.IndexableSetContributor; import com.intellij.util.indexing.IndexedRootsProvider; import junit.framework.TestCase; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -198,7 +199,7 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro runStartupActivities(); } - @Nullable + @NotNull public static Project createProject(File projectFile, String creationPlace) { try { Project project = @@ -251,7 +252,11 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro } protected Module doCreateRealModule(final String moduleName) { - final VirtualFile baseDir = myProject.getBaseDir(); + return doCreateRealModuleIn(moduleName, myProject, getModuleType()); + } + + protected static Module doCreateRealModuleIn(String moduleName, final Project project, final ModuleType moduleType) { + final VirtualFile baseDir = project.getBaseDir(); assertNotNull(baseDir); final File moduleFile = new File(baseDir.getPath().replace('/', File.separatorChar), moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION); @@ -261,7 +266,7 @@ public abstract class PlatformTestCase extends UsefulTestCase implements DataPro @Override protected void run(Result result) throws Throwable { final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(moduleFile); - Module module = ModuleManager.getInstance(myProject).newModule(virtualFile.getPath(), getModuleType()); + Module module = ModuleManager.getInstance(project).newModule(virtualFile.getPath(), moduleType); module.getModuleFile(); result.setResult(module); } diff --git a/platform/testFramework/src/com/intellij/testFramework/TestEditorManagerImpl.java b/platform/testFramework/src/com/intellij/testFramework/TestEditorManagerImpl.java index 1ca79f76ec81..8fe1c8b114e9 100644 --- a/platform/testFramework/src/com/intellij/testFramework/TestEditorManagerImpl.java +++ b/platform/testFramework/src/com/intellij/testFramework/TestEditorManagerImpl.java @@ -66,7 +66,9 @@ import java.util.Map; @Override @NotNull - public Pair openFileWithProviders(@NotNull VirtualFile file, boolean focusEditor) { + public Pair openFileWithProviders(@NotNull VirtualFile file, + boolean focusEditor, + boolean searchForSplitter) { Editor editor = openTextEditor(new OpenFileDescriptor(myProject, file), focusEditor); final FileEditor fileEditor = TextEditorProvider.getInstance().getTextEditor(editor); return Pair.create (new FileEditor[] {fileEditor}, new FileEditorProvider[] {getProvider (fileEditor)}); diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java index 96a5d4f03457..fd6db9fd6662 100644 --- a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java +++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java @@ -589,6 +589,7 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig @Override protected void run() throws Exception { final PsiElement substitution = RenamePsiElementProcessor.forElement(element).substituteElementToRename(element, myEditor); + if (substitution == null) return; new RenameProcessor(myProjectFixture.getProject(), substitution, newName, searchInComments, searchTextOccurrences).run(); } }.execute().throwException(); @@ -1303,7 +1304,7 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig ensureIndexesUpToDate(project); DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project); TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(editor); - return codeAnalyzer.runPasses(file, editor.getDocument(), textEditor, toIgnore, canChangeDocument); + return codeAnalyzer.runPasses(file, editor.getDocument(), textEditor, toIgnore, canChangeDocument,null); } public static void ensureIndexesUpToDate(Project project) { diff --git a/platform/util/src/com/intellij/execution/rmi/RemoteServer.java b/platform/util/src/com/intellij/execution/rmi/RemoteServer.java index 9c512bbdf7dc..1e6a891ded46 100644 --- a/platform/util/src/com/intellij/execution/rmi/RemoteServer.java +++ b/platform/util/src/com/intellij/execution/rmi/RemoteServer.java @@ -23,9 +23,16 @@ import java.rmi.server.UnicastRemoteObject; import java.util.Random; public class RemoteServer { + private static Remote ourRemote; + private static Remote ourStub; + protected static void start(Remote remote) throws Exception { setupRMI(); + if (ourRemote != null) throw new AssertionError("Already started"); + + ourRemote = remote; + Registry registry; int port = 0; for (Random random = new Random(); ;) { @@ -39,9 +46,9 @@ public class RemoteServer { } } try { - final Remote stub = UnicastRemoteObject.exportObject(remote, 0); - final String name = remote.getClass().getSimpleName() + Integer.toHexString(stub.hashCode()); - registry.bind(name, stub); + ourStub = UnicastRemoteObject.exportObject(ourRemote, 0); + final String name = remote.getClass().getSimpleName() + Integer.toHexString(ourStub.hashCode()); + registry.bind(name, ourStub); System.out.println("Port/ID:" + port + "/" + name); Object lock = new Object(); diff --git a/platform/util/src/com/intellij/openapi/progress/ProcessCanceledException.java b/platform/util/src/com/intellij/openapi/progress/ProcessCanceledException.java index 6f322791f3b3..b7c95c87d4c4 100644 --- a/platform/util/src/com/intellij/openapi/progress/ProcessCanceledException.java +++ b/platform/util/src/com/intellij/openapi/progress/ProcessCanceledException.java @@ -17,6 +17,7 @@ package com.intellij.openapi.progress; public class ProcessCanceledException extends RuntimeException { public ProcessCanceledException() { + int i = 0; } public ProcessCanceledException(Throwable cause) { diff --git a/platform/util/src/com/intellij/openapi/util/Comparing.java b/platform/util/src/com/intellij/openapi/util/Comparing.java index d557e31a8ca9..86e7531b8bcf 100644 --- a/platform/util/src/com/intellij/openapi/util/Comparing.java +++ b/platform/util/src/com/intellij/openapi/util/Comparing.java @@ -136,13 +136,36 @@ public class Comparing { public static int hashcode(Object obj) { return obj == null ? 0 : obj.hashCode(); } public static int hashcode(Object obj1, Object obj2) { return hashcode(obj1) ^ hashcode(obj2); } - public static int compare(int name1, int name2) { - return name1 < name2 ? -1 : name1 == name2 ? 0 : 1; + public static int compare(byte o1, byte o2) { + return o1 < o2 ? -1 : o1 == o2 ? 0 : 1; } - public static > int compare(final T name1, final T name2) { - if (name1 == null) return name2 == null ? 0 : -1; - if (name2 == null) return 1; - return name1.compareTo(name2); + public static int compare(int o1, int o2) { + return o1 < o2 ? -1 : o1 == o2 ? 0 : 1; + } + + public static int compare(long o1, long o2) { + return o1 < o2 ? -1 : o1 == o2 ? 0 : 1; + } + + public static int compare(byte[] o1, byte[] o2) { + if (o1 == o2) return 0; + else if (o1 == null) return 1; + else if (o2 == null) return -1; + + if (o1.length > o2.length) return 1; + else if (o1.length < o2.length) return -1; + + for (int i = 0; i < o1.length; i++) { + if (o1[i] > o2[i]) return 1; + else if (o1[i] < o2[i]) return -1; + } + return 0; + } + + public static > int compare(final T o1, final T o2) { + if (o1 == null) return o2 == null ? 0 : -1; + if (o2 == null) return 1; + return o1.compareTo(o2); } } diff --git a/platform/util/src/com/intellij/openapi/util/LowMemoryWatcher.java b/platform/util/src/com/intellij/openapi/util/LowMemoryWatcher.java index 1739d9ac1881..75a12e9a590c 100644 --- a/platform/util/src/com/intellij/openapi/util/LowMemoryWatcher.java +++ b/platform/util/src/com/intellij/openapi/util/LowMemoryWatcher.java @@ -31,6 +31,7 @@ import java.util.concurrent.CopyOnWriteArrayList; * Date: Aug 24, 2010 */ public class LowMemoryWatcher { + private static final long MEM_THRESHOLD = 5 /*MB*/ * 1024 * 1024; public static abstract class ForceableAdapter implements Forceable { public boolean isDirty() { @@ -49,6 +50,7 @@ public class LowMemoryWatcher { static { final Thread thread = new Thread("LowMemoryWatcher") { + boolean shouldCleanup = false; public void run() { updateRef(); final Set> toRemove = new HashSet>(); @@ -57,18 +59,25 @@ public class LowMemoryWatcher { try { ourRefQueue.remove(); updateRef(); - + + if (!shouldCleanup) { + final Runtime runtime = Runtime.getRuntime(); + shouldCleanup = (runtime.maxMemory() - runtime.totalMemory()) <= MEM_THRESHOLD; + } + for (WeakReference instanceRef : ourInstances) { final LowMemoryWatcher watcher = instanceRef.get(); if (watcher == null) { toRemove.add(instanceRef); } else { - try { - watcher.doCleanup(); - } - catch (Throwable e) { - LOG.info(e); + if (shouldCleanup) { + try { + watcher.doCleanup(); + } + catch (Throwable e) { + LOG.info(e); + } } } } diff --git a/platform/util/src/com/intellij/openapi/util/TextRange.java b/platform/util/src/com/intellij/openapi/util/TextRange.java index 83af33e86d94..e0d555ba26af 100644 --- a/platform/util/src/com/intellij/openapi/util/TextRange.java +++ b/platform/util/src/com/intellij/openapi/util/TextRange.java @@ -57,6 +57,10 @@ public class TextRange { return myStartOffset <= startOffset && myEndOffset >= endOffset; } + public boolean containsOffset(int offset) { + return myStartOffset <= offset && offset <= myEndOffset; + } + public String toString() { return "(" + myStartOffset + "," + myEndOffset + ")"; } diff --git a/platform/util/src/com/intellij/util/ParametrizedRunnable.java b/platform/util/src/com/intellij/util/ParameterizedRunnable.java similarity index 93% rename from platform/util/src/com/intellij/util/ParametrizedRunnable.java rename to platform/util/src/com/intellij/util/ParameterizedRunnable.java index 84b449456a40..ea42afc9bcd4 100644 --- a/platform/util/src/com/intellij/util/ParametrizedRunnable.java +++ b/platform/util/src/com/intellij/util/ParameterizedRunnable.java @@ -18,6 +18,6 @@ package com.intellij.util; /** * @author nik */ -public interface ParametrizedRunnable { +public interface ParameterizedRunnable { void run(T t); } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/StringLenComparator.java b/platform/util/src/com/intellij/util/StringLenComparator.java similarity index 97% rename from platform/vcs-impl/src/com/intellij/openapi/vcs/impl/StringLenComparator.java rename to platform/util/src/com/intellij/util/StringLenComparator.java index 56d0eafc96c2..20de59236580 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/StringLenComparator.java +++ b/platform/util/src/com/intellij/util/StringLenComparator.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.intellij.openapi.vcs.impl; +package com.intellij.util; import java.util.Comparator; diff --git a/platform/util/src/com/intellij/util/containers/ContainerUtil.java b/platform/util/src/com/intellij/util/containers/ContainerUtil.java index f93ee99c1d88..cffa2990143a 100644 --- a/platform/util/src/com/intellij/util/containers/ContainerUtil.java +++ b/platform/util/src/com/intellij/util/containers/ContainerUtil.java @@ -782,7 +782,7 @@ public class ContainerUtil { @NotNull public static List map(@NotNull T[] arr, @NotNull Function mapping) { - List result = new ArrayList(); + List result = new ArrayList(arr.length); for (T t : arr) { result.add(mapping.fun(t)); } diff --git a/platform/util/src/com/intellij/util/io/MappedBufferWrapper.java b/platform/util/src/com/intellij/util/io/MappedBufferWrapper.java index b1f0eb7f8412..8114f53e3a3b 100644 --- a/platform/util/src/com/intellij/util/io/MappedBufferWrapper.java +++ b/platform/util/src/com/intellij/util/io/MappedBufferWrapper.java @@ -31,7 +31,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; public abstract class MappedBufferWrapper { - private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.MappedBufferWrapper"); + protected static final Logger LOG = Logger.getInstance("#com.intellij.util.io.MappedBufferWrapper"); @NonNls private static final String CLEANER_METHOD_NAME = "cleaner"; @NonNls private static final String CLEAN_METHOD_NAME = "clean"; diff --git a/platform/util/src/com/intellij/util/io/MappingFailedException.java b/platform/util/src/com/intellij/util/io/MappingFailedException.java new file mode 100644 index 000000000000..6dd91cc3b4d9 --- /dev/null +++ b/platform/util/src/com/intellij/util/io/MappingFailedException.java @@ -0,0 +1,30 @@ +/* + * 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.util.io; + +/** + * @author Eugene Zhuravlev + * Date: 11/24/10 + */ +public class MappingFailedException extends RuntimeException{ + public MappingFailedException(String message) { + super(message); + } + + public MappingFailedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/platform/util/src/com/intellij/util/io/PersistentEnumerator.java b/platform/util/src/com/intellij/util/io/PersistentEnumerator.java index faedb8fee8d8..a71119aa2758 100644 --- a/platform/util/src/com/intellij/util/io/PersistentEnumerator.java +++ b/platform/util/src/com/intellij/util/io/PersistentEnumerator.java @@ -358,6 +358,7 @@ public class PersistentEnumerator implements Forceable { } catch (Throwable e) { markCorrupted(); + LOG.error(e); throw new RuntimeException(e); } } diff --git a/platform/util/src/com/intellij/util/io/ReadOnlyMappedBufferWrapper.java b/platform/util/src/com/intellij/util/io/ReadOnlyMappedBufferWrapper.java index 1544114086ce..f025447395be 100644 --- a/platform/util/src/com/intellij/util/io/ReadOnlyMappedBufferWrapper.java +++ b/platform/util/src/com/intellij/util/io/ReadOnlyMappedBufferWrapper.java @@ -43,7 +43,9 @@ public class ReadOnlyMappedBufferWrapper extends MappedBufferWrapper { } } catch (IOException e) { - throw new RuntimeException("Mapping failed for: " + myFile.getPath(), e); + final MappingFailedException mapFailed = new MappingFailedException("Mapping failed for: " + myFile.getPath(), e); + LOG.error(mapFailed); + throw mapFailed; } } } diff --git a/platform/util/src/com/intellij/util/io/ReadWriteMappedBufferWrapper.java b/platform/util/src/com/intellij/util/io/ReadWriteMappedBufferWrapper.java index e1927b0835a4..1e91397015e3 100644 --- a/platform/util/src/com/intellij/util/io/ReadWriteMappedBufferWrapper.java +++ b/platform/util/src/com/intellij/util/io/ReadWriteMappedBufferWrapper.java @@ -50,7 +50,10 @@ public class ReadWriteMappedBufferWrapper extends MappedBufferWrapper { buf = channel.map(FileChannel.MapMode.READ_WRITE, myPosition, myLength); } catch (IOException e) { - throw new RuntimeException("Mapping failed: " + myFile.getAbsolutePath() + ", position=" + myPosition + ", length=" + myLength, e); + final MappingFailedException mapFailed = + new MappingFailedException("Mapping failed: " + myFile.getAbsolutePath() + ", position=" + myPosition + ", length=" + myLength, e); + LOG.error(mapFailed); + throw mapFailed; } finally { if (channel != null) { @@ -66,7 +69,10 @@ public class ReadWriteMappedBufferWrapper extends MappedBufferWrapper { } if (buf == null) { - throw new RuntimeException("Mapping failed: " + myFile.getAbsolutePath() + ", position=" + myPosition + ", length=" + myLength); + final MappingFailedException mapFailed = + new MappingFailedException("Mapping failed: " + myFile.getAbsolutePath() + ", position=" + myPosition + ", length=" + myLength); + LOG.error(mapFailed); + throw mapFailed; } return buf; diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsRootIterator.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsRootIterator.java index c55c21a4bcc3..18f81ec56503 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsRootIterator.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsRootIterator.java @@ -20,6 +20,7 @@ import com.intellij.openapi.util.Comparing; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Processor; +import com.intellij.util.StringLenComparator; import java.util.*; diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java index 2ed9f463dc4e..413ed78710c0 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XBreakpointType.java @@ -148,12 +148,12 @@ public abstract class XBreakpointType, P extends XBreak /** * Returns properties of the default breakpoint. The default breakpoints cannot be deleted and is always shown on top of the breakpoints - * list in the dialog. It is disabled by default. + * list in the dialog. * - * @return a default breakpoint properties or {@code null} if default breakpoint isn't supported + * @return a default breakpoint or {@code null} if default breakpoint isn't supported */ @Nullable - public P createDefaultBreakpointProperties() { + public XBreakpoint

createDefaultBreakpoint(@NotNull XBreakpointCreator

creator) { return null; } @@ -161,4 +161,9 @@ public abstract class XBreakpointType, P extends XBreak public String getBreakpointsDialogHelpTopic() { return null; } + + public interface XBreakpointCreator

{ + @NotNull + XBreakpoint

createBreakpoint(@Nullable P properties); + } } diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java index c867184bfa0a..a2c6f47ec3ed 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/XLineBreakpointType.java @@ -86,10 +86,10 @@ public abstract class XLineBreakpointType

exten } /** - * Default line breakpoints cannot be supported + * Default line breakpoints aren't supported */ @Override - public final P createDefaultBreakpointProperties() { + public final XLineBreakpoint

createDefaultBreakpoint(@NotNull XBreakpointCreator

creator) { return null; } diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java b/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java index a3662862c63a..3d086269c243 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/evaluation/XDebuggerEvaluator.java @@ -31,14 +31,13 @@ public abstract class XDebuggerEvaluator { /** * Evaluate expression to boolean + * * @param expression expression to evaluate * @return result - * - * @deprecated This method is used to evaluate breakpoints' conditions only. Instead of implementing it you should evaluate breakpoint's condition - * in your code and call {@link XDebugSession#breakpointReached(XBreakpoint, XSuspendContext)} - * only if the condition evaluates to true. - * * @see XBreakpoint#getCondition() + * @deprecated This method is used to evaluate breakpoints' conditions only. Instead of implementing it you should evaluate breakpoint's condition + * in your code and call {@link XDebugSession#breakpointReached(XBreakpoint, XSuspendContext)} + * only if the condition evaluates to true. */ @Deprecated public boolean evaluateCondition(@NotNull String expression) { @@ -47,11 +46,11 @@ public abstract class XDebuggerEvaluator { /** * Evaluate expression to string + * * @param expression expression to evaluate * @return result - * * @deprecated This method is used to evaluate breakpoints' log messages only. Instead of implementing it you should evaluate breakpoint's - * log message in your code and pass it to {@link XDebugSession#breakpointReached(XBreakpoint, String, XSuspendContext)}. + * log message in your code and pass it to {@link XDebugSession#breakpointReached(XBreakpoint, String, XSuspendContext)}. */ @Deprecated @Nullable @@ -61,8 +60,9 @@ public abstract class XDebuggerEvaluator { /** * Start evaluating expression. + * * @param expression expression to evaluate - * @param callback used to notify that the expression has been evaluated or an error occurs + * @param callback used to notify that the expression has been evaluated or an error occurs */ public void evaluate(@NotNull String expression, XEvaluationCallback callback, @Nullable XSourcePosition expressionPosition) { evaluate(expression, callback); @@ -77,9 +77,10 @@ public abstract class XDebuggerEvaluator { /** * Return text range of expression which can be evaluated. - * @param project project + * + * @param project project * @param document document - * @param offset offset + * @param offset offset * @return text range of expression */ @Nullable diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointManagerImpl.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointManagerImpl.java index 08a4edf99255..b411afdfb3f9 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointManagerImpl.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointManagerImpl.java @@ -107,17 +107,15 @@ public class XBreakpointManagerImpl implements XBreakpointManager, PersistentSta @NotNull public XBreakpoint addBreakpoint(final XBreakpointType,T> type, @Nullable final T properties) { ApplicationManager.getApplication().assertWriteAccessAllowed(); - return addBreakpoint(type, properties, false, true); + XBreakpointBase breakpoint = createBreakpoint(type, properties, true); + addBreakpoint(breakpoint, false, true); + return breakpoint; } - private XBreakpointBase addBreakpoint(XBreakpointType, T> type, - T properties, - final boolean defaultBreakpoint, - final boolean initUI) { - XBreakpointBase.BreakpointState state = new XBreakpointBase.BreakpointState,T,XBreakpointType,T>>(!defaultBreakpoint, type.getId()); - XBreakpointBase breakpoint = new XBreakpointBase,T, XBreakpointBase.BreakpointState>(type, this, properties, state); - addBreakpoint(breakpoint, defaultBreakpoint, initUI); - return breakpoint; + private XBreakpointBase createBreakpoint(XBreakpointType, T> type, + T properties, final boolean enabled) { + XBreakpointBase.BreakpointState state = new XBreakpointBase.BreakpointState,T,XBreakpointType,T>>(enabled, type.getId()); + return new XBreakpointBase,T, XBreakpointBase.BreakpointState>(type, this, properties, state); } private void addBreakpoint(final XBreakpointBase breakpoint, final boolean defaultBreakpoint, @@ -295,14 +293,14 @@ public class XBreakpointManagerImpl implements XBreakpointManager, PersistentSta return state; } - private static

boolean differsFromDefault(XBreakpointType type, + private

boolean differsFromDefault(XBreakpointType type, XBreakpointBase.BreakpointState state) { - final P defaultProperties = type.createDefaultBreakpointProperties(); - if (defaultProperties == null) { + final XBreakpoint

defaultBreakpoint = createDefaultBreakpoint(type); + if (defaultBreakpoint == null) { return false; } - XBreakpointBase.BreakpointState defaultState = new XBreakpointBase.BreakpointState(false, type.getId()); - defaultState.setPropertiesElement(XmlSerializer.serialize(defaultProperties)); + + XBreakpointBase.BreakpointState defaultState = ((XBreakpointBase)defaultBreakpoint).getState(); Element defaultElement = XmlSerializer.serialize(defaultState, SERIALIZATION_FILTER); Element currentElement = XmlSerializer.serialize(state, SERIALIZATION_FILTER); return !JDOMUtil.areElementsEqual(defaultElement, currentElement); @@ -338,13 +336,24 @@ public class XBreakpointManagerImpl implements XBreakpointManager, PersistentSta } private

void addDefaultBreakpoint(XBreakpointType type) { - final P properties = type.createDefaultBreakpointProperties(); - if (properties != null) { - //noinspection unchecked - addBreakpoint((XBreakpointType, P>)type, properties, true, false); + final XBreakpoint

breakpoint = createDefaultBreakpoint(type); + if (breakpoint != null) { + addBreakpoint((XBreakpointBase)breakpoint, true, false); } } + @Nullable + private

XBreakpoint

createDefaultBreakpoint(final XBreakpointType, P> type) { + return type.createDefaultBreakpoint(new XBreakpointType.XBreakpointCreator

() { + @NotNull + @Override + public XBreakpoint

createBreakpoint(@Nullable P properties) { + //noinspection unchecked + return XBreakpointManagerImpl.this.createBreakpoint((XBreakpointType, P>)type, properties, false); + } + }); + } + private void loadBreakpoint(XBreakpointBase.BreakpointState breakpointState, final boolean defaultBreakpoint) { XBreakpointBase breakpoint = createBreakpoint(breakpointState); if (breakpoint != null) { diff --git a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointManagerTest.java b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointManagerTest.java index a6e23eb0fee2..904f0e2ddf1a 100644 --- a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointManagerTest.java +++ b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XBreakpointManagerTest.java @@ -62,6 +62,7 @@ public class XBreakpointManagerTest extends XBreakpointsTestCase { assertTrue(myBreakpointManager.isDefaultBreakpoint(breakpoints[0])); assertEquals("default", assertInstanceOf(breakpoints[0].getProperties(), MyBreakpointProperties.class).myOption); + assertTrue(breakpoints[0].isEnabled()); XLineBreakpoint lineBreakpoint = assertInstanceOf(breakpoints[1], XLineBreakpoint.class); assertEquals(239, lineBreakpoint.getLine()); @@ -85,14 +86,14 @@ public class XBreakpointManagerTest extends XBreakpointsTestCase { assertEquals(0, element.getContent().size()); } - public void testSaveEnabledDefaultBreakpoint() throws Exception { + public void testSaveChangedDefaultBreakpoint() throws Exception { reload(); final XBreakpoint breakpoint = getSingleBreakpoint(); - breakpoint.setEnabled(true); + breakpoint.setEnabled(false); assertFalse(save().getContent().isEmpty()); reload(); - assertTrue(getSingleBreakpoint().isEnabled()); + assertFalse(getSingleBreakpoint().isEnabled()); } public void testSaveDefaultBreakpointWithModifiedProperties() throws Exception { diff --git a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestCase.java b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestCase.java index d6b37c35569c..8f67ac31a34b 100644 --- a/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestCase.java +++ b/platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestCase.java @@ -25,10 +25,7 @@ import com.intellij.openapi.vfs.ex.http.HttpFileSystem; import com.intellij.openapi.vfs.impl.http.HttpFileSystemImpl; import com.intellij.testFramework.PlatformLiteFixture; import com.intellij.util.xmlb.annotations.Attribute; -import com.intellij.xdebugger.breakpoints.XBreakpoint; -import com.intellij.xdebugger.breakpoints.XBreakpointProperties; -import com.intellij.xdebugger.breakpoints.XBreakpointType; -import com.intellij.xdebugger.breakpoints.XLineBreakpointType; +import com.intellij.xdebugger.breakpoints.*; import org.jetbrains.annotations.NotNull; import org.picocontainer.MutablePicoContainer; @@ -90,8 +87,10 @@ public abstract class XDebuggerTestCase extends PlatformLiteFixture { } @Override - public MyBreakpointProperties createDefaultBreakpointProperties() { - return new MyBreakpointProperties("default"); + public XBreakpoint createDefaultBreakpoint(@NotNull XBreakpointCreator creator) { + final XBreakpoint breakpoint = creator.createBreakpoint(new MyBreakpointProperties("default")); + breakpoint.setEnabled(true); + return breakpoint; } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties b/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties index 6b901db9bbb5..7f092ffbebc7 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties +++ b/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties @@ -1810,3 +1810,4 @@ unnecesarily.qualified.statically.imported.element.display.name=Unnecessarily qu unnecesarily.qualified.statically.imported.element.problem.descriptor=Statically imported element ''{0}'' is unnecessarily qualified with #ref #loc unnecesarily.qualified.statically.imported.element.quickfix=Remove unnecessary qualifier ignore.instanceof.on.library.classes=ignore instanceof on library classes +assertequals.may.be.assertsame.quickfix=Replace with 'assertSame()' diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/abstraction/PublicMethodNotExposedInInterfaceInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/abstraction/PublicMethodNotExposedInInterfaceInspection.java index 4faa157f4e71..7a71eb61609a 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/abstraction/PublicMethodNotExposedInInterfaceInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/abstraction/PublicMethodNotExposedInInterfaceInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.abstraction; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiModifier; @@ -27,18 +28,21 @@ import org.jetbrains.annotations.NotNull; public class PublicMethodNotExposedInInterfaceInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "public.method.not.in.interface.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "public.method.not.in.interface.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new PublicMethodNotExposedInInterface(); } @@ -81,14 +85,17 @@ public class PublicMethodNotExposedInInterfaceInspection } private static boolean exposedInInterface(PsiMethod method) { - final PsiMethod[] superMethods = method.findSuperMethods(); + final PsiMethod[] superMethods = method.findSuperMethods(); for(final PsiMethod superMethod : superMethods) { final PsiClass superClass = superMethod.getContainingClass(); + if (superClass == null) { + continue; + } if(superClass.isInterface()) { return true; } final String superclassName = superClass.getQualifiedName(); - if("java.lang.Object".equals(superclassName)) { + if(CommonClassNames.JAVA_LANG_OBJECT.equals(superclassName)) { return true; } if(exposedInInterface(superMethod)) { diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/abstraction/TypeMayBeWeakenedInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/abstraction/TypeMayBeWeakenedInspection.java index 65ce2308d392..890f3cdb6495 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/abstraction/TypeMayBeWeakenedInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/abstraction/TypeMayBeWeakenedInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2009 Bas Leijdekkers + * Copyright 2006-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -273,7 +273,7 @@ public class TypeMayBeWeakenedInspection extends BaseInspection { final Project project = variable.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final PsiClass javaLangObjectClass = - facade.findClass("java.lang.Object", + facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, variable.getResolveScope()); weakestClasses.remove(javaLangObjectClass); } @@ -320,7 +320,7 @@ public class TypeMayBeWeakenedInspection extends BaseInspection { final Project project = method.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final PsiClass javaLangObjectClass = - facade.findClass("java.lang.Object", + facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, method.getResolveScope()); weakestClasses.remove(javaLangObjectClass); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/assignment/AssignmentToDateFieldFromParameterInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/assignment/AssignmentToDateFieldFromParameterInspection.java index fb8b1e389245..3e216d306f32 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/assignment/AssignmentToDateFieldFromParameterInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/assignment/AssignmentToDateFieldFromParameterInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,7 +81,8 @@ public class AssignmentToDateFieldFromParameterInspection return; } final String type = TypeUtils.expressionHasTypeOrSubtype(lhs, - "java.util.Date", "java.util.Calendar"); + CommonClassNames.JAVA_UTIL_DATE, + CommonClassNames.JAVA_UTIL_CALENDAR); if (type == null) { return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bitwise/PointlessBitwiseExpressionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bitwise/PointlessBitwiseExpressionInspection.java index 0e3897e4fca3..fc6cf4d696f7 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bitwise/PointlessBitwiseExpressionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bitwise/PointlessBitwiseExpressionInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,12 +50,14 @@ public class PointlessBitwiseExpressionInspection extends BaseInspection { bitwiseTokens.add(">>>"); } + @Override @NotNull public String getDisplayName(){ return InspectionGadgetsBundle.message( "pointless.bitwise.expression.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos){ final String replacementExpression = @@ -65,10 +67,12 @@ public class PointlessBitwiseExpressionInspection extends BaseInspection { replacementExpression); } + @Override public boolean isEnabledByDefault(){ return true; } + @Override public JComponent createOptionsPanel(){ return new SingleCheckboxOptionsPanel( InspectionGadgetsBundle.message( @@ -115,10 +119,12 @@ public class PointlessBitwiseExpressionInspection extends BaseInspection { } } + @Override public BaseInspectionVisitor buildVisitor(){ return new PointlessBitwiseVisitor(); } + @Override public InspectionGadgetsFix buildFix(Object... infos){ return new PointlessBitwiseFix(); } @@ -131,6 +137,7 @@ public class PointlessBitwiseExpressionInspection extends BaseInspection { "pointless.bitwise.expression.simplify.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException{ final PsiExpression expression = (PsiExpression) descriptor @@ -160,7 +167,7 @@ public class PointlessBitwiseExpressionInspection extends BaseInspection { return; } if(rhsType.equals(PsiType.BOOLEAN) || - rhsType.equalsToText("java.lang.Boolean")){ + rhsType.equalsToText(CommonClassNames.JAVA_LANG_BOOLEAN)){ return; } final PsiExpression lhs = expression.getLOperand(); @@ -169,7 +176,7 @@ public class PointlessBitwiseExpressionInspection extends BaseInspection { return; } if(lhsType.equals(PsiType.BOOLEAN) || - lhsType.equalsToText("java.lang.Boolean")){ + lhsType.equalsToText(CommonClassNames.JAVA_LANG_BOOLEAN)){ return; } final IElementType tokenType = sign.getTokenType(); @@ -235,18 +242,18 @@ public class PointlessBitwiseExpressionInspection extends BaseInspection { if(value == null){ return false; } - if(value instanceof Integer && ((Integer) value) == 0xffffffff){ + if(value instanceof Integer && ((Integer) value).intValue() == 0xffffffff){ return true; } - if(value instanceof Long && ((Long) value) == 0xffffffffffffffffL){ + if(value instanceof Long && ((Long) value).longValue() == 0xffffffffffffffffL){ return true; } - if(value instanceof Short && ((Short) value) == (short) 0xffff){ + if(value instanceof Short && ((Short) value).shortValue() == (short) 0xffff){ return true; } - if(value instanceof Character && ((Character) value) == (char) 0xffff){ + if(value instanceof Character && ((Character) value).charValue() == (char) 0xffff){ return true; } - return value instanceof Byte && ((Byte) value) == (byte) 0xff; + return value instanceof Byte && ((Byte) value).byteValue() == (byte) 0xff; } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ArchaicSystemPropertyAccessInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ArchaicSystemPropertyAccessInspection.java index 11ffea94221e..bf5c50199916 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ArchaicSystemPropertyAccessInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ArchaicSystemPropertyAccessInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,17 +29,20 @@ import org.jetbrains.annotations.NotNull; public class ArchaicSystemPropertyAccessInspection extends BaseInspection { + @Override @NotNull public String getID(){ return "UseOfArchaicSystemPropertyAccessors"; } + @Override @NotNull public String getDisplayName(){ return InspectionGadgetsBundle.message( "archaic.system.property.accessors.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos){ final PsiMethodCallExpression call = @@ -56,6 +59,7 @@ public class ArchaicSystemPropertyAccessInspection extends BaseInspection { } } + @Override @NotNull protected InspectionGadgetsFix[] buildFixes(Object... infos){ return new InspectionGadgetsFix[]{new ReplaceWithParseMethodFix(), @@ -70,6 +74,7 @@ public class ArchaicSystemPropertyAccessInspection extends BaseInspection { "archaic.system.property.accessors.replace.parse.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException{ final PsiIdentifier location = @@ -104,6 +109,7 @@ public class ArchaicSystemPropertyAccessInspection extends BaseInspection { "archaic.system.property.accessors.replace.standard.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException{ final PsiIdentifier location = @@ -137,6 +143,7 @@ public class ArchaicSystemPropertyAccessInspection extends BaseInspection { } + @Override public BaseInspectionVisitor buildVisitor(){ return new ArchaicSystemPropertyAccessVisitor(); } @@ -156,15 +163,17 @@ public class ArchaicSystemPropertyAccessInspection extends BaseInspection { } static boolean isIntegerGetInteger(PsiMethodCallExpression expression){ - return isCallTo(expression, "java.lang.Integer", "getInteger"); + return isCallTo(expression, CommonClassNames.JAVA_LANG_INTEGER, + "getInteger"); } static boolean isLongGetLong(PsiMethodCallExpression expression){ - return isCallTo(expression, "java.lang.Long", "getLong"); + return isCallTo(expression, CommonClassNames.JAVA_LANG_LONG, "getLong"); } static boolean isBooleanGetBoolean(PsiMethodCallExpression expression){ - return isCallTo(expression, "java.lang.Boolean", "getBoolean"); + return isCallTo(expression, CommonClassNames.JAVA_LANG_BOOLEAN, + "getBoolean"); } private static boolean isCallTo(PsiMethodCallExpression expression, diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ClassNewInstanceInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ClassNewInstanceInspection.java index 5d3b8a16bea9..e9b839ef4109 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ClassNewInstanceInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ClassNewInstanceInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2009 Bas Leijdekkers + * Copyright 2009-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix;import com.siyeh.InspectionGadgetsBundle; import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.Set; @@ -33,6 +34,7 @@ import java.util.HashSet; public class ClassNewInstanceInspection extends BaseInspection { + @Override @Nls @NotNull public String getDisplayName() { @@ -40,6 +42,7 @@ public class ClassNewInstanceInspection extends BaseInspection { "class.new.instance.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( @@ -59,6 +62,7 @@ public class ClassNewInstanceInspection extends BaseInspection { "class.new.instance.quickfix"); } + @Override protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); @@ -89,10 +93,9 @@ public class ClassNewInstanceInspection extends BaseInspection { addThrowsClause(method, "java.lang.NoSuchMethodException", "java.lang.reflect.InvocationTargetException"); } - System.out.println("parentOfType: " + parentOfType); final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent; - final String newExpression = qualifier.getText() + + @NonNls final String newExpression = qualifier.getText() + ".getConstructor().newInstance()"; replaceExpression(methodCallExpression, newExpression); @@ -159,6 +162,7 @@ public class ClassNewInstanceInspection extends BaseInspection { } } + @Override public BaseInspectionVisitor buildVisitor() { return new ClassNewInstanceVisitor(); } @@ -170,7 +174,7 @@ public class ClassNewInstanceInspection extends BaseInspection { PsiMethodCallExpression expression) { final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); + @NonNls final String methodName = methodExpression.getReferenceName(); if (!"newInstance".equals(methodName)) { return; } @@ -189,7 +193,7 @@ public class ClassNewInstanceInspection extends BaseInspection { return; } final String className = aClass.getQualifiedName(); - if (!"java.lang.Class".equals(className)) { + if (!CommonClassNames.JAVA_LANG_CLASS.equals(className)) { return; } registerMethodCallError(expression); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/CollectionAddedToSelfInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/CollectionAddedToSelfInspection.java index 4cf81d0e4c4c..dc5ff5783f1f 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/CollectionAddedToSelfInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/CollectionAddedToSelfInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,18 +26,21 @@ import org.jetbrains.annotations.NotNull; public class CollectionAddedToSelfInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "collection.added.to.self.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "collection.added.to.self.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new CollectionAddedToSelfVisitor(); } @@ -88,8 +91,10 @@ public class CollectionAddedToSelfInspection extends BaseInspection { if(qualifierClass == null){ return; } - if(!ClassUtils.isSubclass(qualifierClass, "java.util.Collection") && - !ClassUtils.isSubclass(qualifierClass, "java.util.Map")) { + if(!ClassUtils.isSubclass(qualifierClass, + CommonClassNames.JAVA_UTIL_COLLECTION) && + !ClassUtils.isSubclass(qualifierClass, + CommonClassNames.JAVA_UTIL_MAP)) { return; } registerError(qualifier); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ComparableImplementedButEqualsNotOverriddenInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ComparableImplementedButEqualsNotOverriddenInspection.java index 85c8c5b73b82..00cd18f27ce3 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ComparableImplementedButEqualsNotOverriddenInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ComparableImplementedButEqualsNotOverriddenInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 Bas Leijdekkers + * Copyright 2006-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,9 @@ */ package com.siyeh.ig.bugs; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiManager; -import com.intellij.psi.PsiMethod; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.MethodSignatureUtil; import com.siyeh.HardcodedMethodConstants; import com.siyeh.InspectionGadgetsBundle; @@ -30,18 +29,21 @@ import org.jetbrains.annotations.NotNull; public class ComparableImplementedButEqualsNotOverriddenInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "comparable.implemented.but.equals.not.overridden.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "comparable.implemented.but.equals.not.overridden.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new CompareToAndEqualsNotPairedVisitor(); } @@ -56,9 +58,12 @@ public class ComparableImplementedButEqualsNotOverriddenInspection if (methods.length == 0) { return; } - final PsiManager manager = aClass.getManager(); - final PsiClass comparableClass = - JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.Comparable", aClass.getResolveScope()); + final Project project = aClass.getProject(); + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); + final GlobalSearchScope scope = aClass.getResolveScope(); + final PsiClass comparableClass = + psiFacade.findClass(CommonClassNames.JAVA_LANG_COMPARABLE, + scope); if (comparableClass == null) { return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ComparatorMethodParameterNotUsedInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ComparatorMethodParameterNotUsedInspection.java index 9e08a180c20f..95a3c49ff3eb 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ComparatorMethodParameterNotUsedInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ComparatorMethodParameterNotUsedInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 Bas Leijdekkers + * Copyright 2007-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,22 +28,26 @@ import java.util.*; public class ComparatorMethodParameterNotUsedInspection extends BaseInspection { + @Override @Nls @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "comparator.method.parameter.not.used.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "comparator.method.parameter.not.used.problem.descriptor"); } + @Override public boolean isEnabledByDefault() { return true; } + @Override public BaseInspectionVisitor buildVisitor() { return new CompareMethodDoesNotUseParameterVisitor(); } @@ -53,7 +57,8 @@ public class ComparatorMethodParameterNotUsedInspection @Override public void visitMethod(PsiMethod method) { super.visitMethod(method); - if (!MethodUtils.methodMatches(method, "java.util.Comparator", + if (!MethodUtils.methodMatches(method, + CommonClassNames.JAVA_UTIL_COMPARATOR, PsiType.INT, "compare", PsiType.NULL, PsiType.NULL)) { return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/CovariantCompareToInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/CovariantCompareToInspection.java index 420a67c3fef0..8e632a5d5e23 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/CovariantCompareToInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/CovariantCompareToInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,18 +29,21 @@ import org.jetbrains.annotations.NotNull; public class CovariantCompareToInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "covariant.compareto.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "covariant.compareto.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new CovariantCompareToVisitor(); } @@ -77,9 +80,12 @@ public class CovariantCompareToInspection extends BaseInspection { return; } } - final PsiManager manager = method.getManager(); - final PsiClass comparableClass = - JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.Comparable", method.getResolveScope()); + final Project project = method.getProject(); + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); + final GlobalSearchScope scope = method.getResolveScope(); + final PsiClass comparableClass = + psiFacade.findClass(CommonClassNames.JAVA_LANG_COMPARABLE, + scope); if (comparableClass != null && comparableClass.getTypeParameters().length == 1) { final PsiSubstitutor superSubstitutor = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/FormatDecode.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/FormatDecode.java index a745af6402fa..ec750545ffe5 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/FormatDecode.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/FormatDecode.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.bugs; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiType; import java.util.ArrayList; @@ -154,9 +155,10 @@ class FormatDecode{ public boolean valid(PsiType type){ final String text = type.getCanonicalText(); - return PsiType.LONG.equals(type) || "java.lang.Long".equals(text) || - "java.util.Date".equals(text) || - "java.util.Calendar".equals(text); + return PsiType.LONG.equals(type) || + CommonClassNames.JAVA_LANG_LONG.equals(text) || + CommonClassNames.JAVA_UTIL_DATE.equals(text) || + CommonClassNames.JAVA_UTIL_CALENDAR.equals(text); } public String type(){ @@ -169,7 +171,7 @@ class FormatDecode{ public boolean valid(PsiType type){ final String text = type.getCanonicalText(); return PsiType.CHAR.equals(type) || - "java.lang.Character".equals(text); + CommonClassNames.JAVA_LANG_CHARACTER.equals(text); } public String type(){ @@ -181,10 +183,14 @@ class FormatDecode{ public boolean valid(PsiType type){ final String text = type.getCanonicalText(); - return PsiType.INT.equals(type) || "java.lang.Integer".equals(text) || - PsiType.LONG.equals(type) || "java.lang.Long".equals(text) || - PsiType.SHORT.equals(type) || "java.lang.Short".equals(text) || - PsiType.BYTE.equals(type) || "java.lang.Byte".equals(text) || + return PsiType.INT.equals(type) || + CommonClassNames.JAVA_LANG_INTEGER.equals(text) || + PsiType.LONG.equals(type) || + CommonClassNames.JAVA_LANG_LONG.equals(text) || + PsiType.SHORT.equals(type) || + CommonClassNames.JAVA_LANG_SHORT.equals(text) || + PsiType.BYTE.equals(type) || + CommonClassNames.JAVA_LANG_BYTE.equals(text) || "java.math.BigInteger".equals(text); } @@ -197,8 +203,10 @@ class FormatDecode{ public boolean valid(PsiType type){ final String text = type.getCanonicalText(); - return PsiType.DOUBLE.equals(type) || "java.lang.Double".equals(text) || - PsiType.FLOAT.equals(type) || "java.lang.Float".equals(text) || + return PsiType.DOUBLE.equals(type) || + CommonClassNames.JAVA_LANG_DOUBLE.equals(text) || + PsiType.FLOAT.equals(type) || + CommonClassNames.JAVA_LANG_FLOAT.equals(text) || "java.math.BigDecimal".equals(text); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ImplicitArrayToStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ImplicitArrayToStringInspection.java index 5fb7958c8edb..6c2432a3d0c4 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ImplicitArrayToStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ImplicitArrayToStringInspection.java @@ -160,13 +160,13 @@ public class ImplicitArrayToStringInspection extends BaseInspection { if (!lhs.equals(expression)) { final PsiType lhsType = lhs.getType(); return !(lhsType == null || - !lhsType.equalsToText("java.lang.String")); + !lhsType.equalsToText(CommonClassNames.JAVA_LANG_STRING)); } final PsiExpression rhs = binaryExpression.getROperand(); if (rhs != null && !rhs.equals(expression)) { final PsiType rhsType = rhs.getType(); return !(rhsType == null || - !rhsType.equalsToText("java.lang.String")); + !rhsType.equalsToText(CommonClassNames.JAVA_LANG_STRING)); } } else if (parent instanceof PsiExpressionList) { final PsiExpressionList expressionList = @@ -231,7 +231,7 @@ public class ImplicitArrayToStringInspection extends BaseInspection { } final PsiClass aClass = (PsiClass)target; final String className = aClass.getQualifiedName(); - if (!"java.lang.String".equals(className)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { return false; } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/IteratorHasNextCallsIteratorNextInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/IteratorHasNextCallsIteratorNextInspection.java index 3a7f13a5651f..a65b544fc7da 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/IteratorHasNextCallsIteratorNextInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/IteratorHasNextCallsIteratorNextInspection.java @@ -15,6 +15,7 @@ */ package com.siyeh.ig.bugs; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiMethod; import com.siyeh.HardcodedMethodConstants; import com.siyeh.InspectionGadgetsBundle; @@ -50,7 +51,7 @@ public class IteratorHasNextCallsIteratorNextInspection @Override public void visitMethod(@NotNull PsiMethod method){ // note: no call to super @NonNls final String name = method.getName(); - if (!MethodUtils.methodMatches(method, "java.util.Iterator", null, + if (!MethodUtils.methodMatches(method, CommonClassNames.JAVA_UTIL_ITERATOR, null, HardcodedMethodConstants.HAS_NEXT)) { return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/IteratorNextDoesNotThrowNoSuchElementExceptionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/IteratorNextDoesNotThrowNoSuchElementExceptionInspection.java index c1d10f12f3a4..7ab6fa02594e 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/IteratorNextDoesNotThrowNoSuchElementExceptionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/IteratorNextDoesNotThrowNoSuchElementExceptionInspection.java @@ -60,7 +60,7 @@ public class IteratorNextDoesNotThrowNoSuchElementExceptionInspection @Override public void visitMethod(@NotNull PsiMethod method){ // note: no call to super - if (!MethodUtils.methodMatches(method, "java.util.Iterator", null, + if (!MethodUtils.methodMatches(method, CommonClassNames.JAVA_UTIL_ITERATOR, null, HardcodedMethodConstants.NEXT)) { return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedFormatStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedFormatStringInspection.java index cac3195123ff..c99bf967f377 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedFormatStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedFormatStringInspection.java @@ -41,13 +41,11 @@ public class MalformedFormatStringInspection extends BaseInspection{ @NotNull public String buildErrorString(Object... infos){ final Object value = infos[0]; - final Validator[] validators; if (value instanceof Exception) { return InspectionGadgetsBundle.message( "malformed.format.string.problem.descriptor.malformed"); - } else { - validators = (Validator[]) value; } + final Validator[] validators = (Validator[]) value; final int argumentCount = ((Integer)infos[1]).intValue(); if(validators.length < argumentCount){ return InspectionGadgetsBundle.message( @@ -90,7 +88,7 @@ public class MalformedFormatStringInspection extends BaseInspection{ formatClassNames.add("java.io.PrintWriter"); formatClassNames.add("java.io.PrintStream"); formatClassNames.add("java.util.Formatter"); - formatClassNames.add("java.lang.String"); + formatClassNames.add(CommonClassNames.JAVA_LANG_STRING); } @Override public void visitMethodCallExpression( @@ -115,7 +113,7 @@ public class MalformedFormatStringInspection extends BaseInspection{ } final PsiExpression formatArgument = arguments[formatArgPosition]; if(!TypeUtils.expressionHasType(formatArgument, - "java.lang.String")) { + CommonClassNames.JAVA_LANG_STRING)) { return; } if(!PsiUtil.isConstantExpression(formatArgument)){ diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedRegexInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedRegexInspection.java index 228a5d570f1e..de615efa79e7 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedRegexInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedRegexInspection.java @@ -15,10 +15,7 @@ */ package com.siyeh.ig.bugs; -import com.intellij.psi.PsiExpression; -import com.intellij.psi.PsiExpressionList; -import com.intellij.psi.PsiMethodCallExpression; -import com.intellij.psi.PsiType; +import com.intellij.psi.*; import com.intellij.psi.util.ConstantExpressionUtil; import com.intellij.psi.util.PsiUtil; import com.siyeh.InspectionGadgetsBundle; @@ -77,7 +74,8 @@ public class MalformedRegexInspection extends BaseInspection { return; } final PsiExpression argument = arguments[0]; - if(!TypeUtils.expressionHasType(argument, "java.lang.String")){ + if(!TypeUtils.expressionHasType(argument, + CommonClassNames.JAVA_LANG_STRING)){ return; } if(!PsiUtil.isConstantExpression(argument)){ diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedXPathInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedXPathInspection.java index c4ac2014cae2..50ac9f05f085 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedXPathInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MalformedXPathInspection.java @@ -77,7 +77,8 @@ public class MalformedXPathInspection extends BaseInspection { return; } final PsiExpression xpathArgument = arguments[0]; - if(!TypeUtils.expressionHasType(xpathArgument, "java.lang.String")){ + if(!TypeUtils.expressionHasType(xpathArgument, + CommonClassNames.JAVA_LANG_STRING)){ return; } if(!PsiUtil.isConstantExpression(xpathArgument)){ diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/NewStringBufferWithCharArgumentInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/NewStringBufferWithCharArgumentInspection.java index 789e8d310c00..e0934e695584 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/NewStringBufferWithCharArgumentInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/NewStringBufferWithCharArgumentInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2007-2008 Bas Leijdekkers + * Copyright 2007-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ import org.jetbrains.annotations.Nullable; public class NewStringBufferWithCharArgumentInspection extends BaseInspection { + @Override @Nls @NotNull public String getDisplayName() { @@ -37,16 +38,19 @@ public class NewStringBufferWithCharArgumentInspection extends BaseInspection { "new.string.buffer.with.char.argument.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "new.string.buffer.with.char.argument.problem.descriptor"); } + @Override public boolean isEnabledByDefault() { return true; } + @Override @Nullable protected InspectionGadgetsFix buildFix(Object... infos) { final PsiExpression argument = (PsiExpression) infos[0]; @@ -65,6 +69,7 @@ public class NewStringBufferWithCharArgumentInspection extends BaseInspection { "new.string.buffer.with.char.argument.quickfix"); } + @Override protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); @@ -87,6 +92,7 @@ public class NewStringBufferWithCharArgumentInspection extends BaseInspection { } } + @Override public BaseInspectionVisitor buildVisitor() { return new StringBufferWithCharArgumentVisitor(); } @@ -115,7 +121,7 @@ public class NewStringBufferWithCharArgumentInspection extends BaseInspection { } final PsiClass aClass = constructor.getContainingClass(); if (!ClassUtils.isSubclass(aClass, - "java.lang.AbstractStringBuilder")) { + CommonClassNames.JAVA_LANG_ABSTRACT_STRING_BUILDER)) { return; } registerNewExpressionError(expression, argument); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/NumberEqualityInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/NumberEqualityInspection.java index c7f86441d9b0..3d9b4922c0c4 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/NumberEqualityInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/NumberEqualityInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,26 +27,31 @@ import org.jetbrains.annotations.NotNull; public class NumberEqualityInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "number.comparison.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "number.comparison.problem.descriptor"); } + @Override public boolean isEnabledByDefault(){ return true; } + @Override public BaseInspectionVisitor buildVisitor() { return new ObjectEqualityVisitor(); } + @Override public InspectionGadgetsFix buildFix(Object... infos) { return new EqualityToEqualsFix(); } @@ -86,7 +91,8 @@ public class NumberEqualityInspection extends BaseInspection { } private static boolean hasNumberType(PsiExpression lhs) { - return TypeUtils.expressionHasTypeOrSubtype(lhs, "java.lang.Number"); + return TypeUtils.expressionHasTypeOrSubtype(lhs, + CommonClassNames.JAVA_LANG_NUMBER); } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ObjectEqualityInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ObjectEqualityInspection.java index 9a384d488e19..09b2854b1589 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ObjectEqualityInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ObjectEqualityInspection.java @@ -204,13 +204,13 @@ public class ObjectEqualityInspection extends BaseInspection { } final PsiClassType classType = (PsiClassType) type; final PsiClassType rawType = classType.rawType(); - return rawType.equalsToText("java.lang.Class"); + return rawType.equalsToText(CommonClassNames.JAVA_LANG_CLASS); } private boolean isEnumType(@Nullable PsiExpression expression) { return expression != null && TypeUtils.expressionHasTypeOrSubtype(expression, - "java.lang.Enum"); + CommonClassNames.JAVA_LANG_ENUM); } private boolean isObjectType(PsiExpression expression) { @@ -223,7 +223,7 @@ public class ObjectEqualityInspection extends BaseInspection { !(type instanceof PsiPrimitiveType) && !TypeUtils.isJavaLangString(type) && !TypeUtils.expressionHasTypeOrSubtype(expression, - "java.lang.Number"); + CommonClassNames.JAVA_LANG_NUMBER); } } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ObjectToStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ObjectToStringInspection.java index d716bd901deb..f38e1981989d 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ObjectToStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ObjectToStringInspection.java @@ -112,7 +112,7 @@ public class ObjectToStringInspection extends BaseInspection { final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (!TypeUtils.expressionHasTypeOrSubtype(qualifier, - "java.lang.AbstractStringBuilder")) { + CommonClassNames.JAVA_LANG_ABSTRACT_STRING_BUILDER)) { return; } final PsiExpressionList argumentList = @@ -133,7 +133,7 @@ public class ObjectToStringInspection extends BaseInspection { (PsiReferenceExpression) qualifierExpression; final String canonicalText = referenceExpression.getCanonicalText(); - if (!"java.lang.String".equals(canonicalText)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(canonicalText)) { return; } final PsiExpressionList argumentList = @@ -163,7 +163,7 @@ public class ObjectToStringInspection extends BaseInspection { return; } final PsiClassType classType = (PsiClassType) type; - if (type.equalsToText("java.lang.Object")) { + if (type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { return; } final PsiClass referencedClass = classType.resolve(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ParameterClassCheckVisitor.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ParameterClassCheckVisitor.java index 509b84271141..9940e5b58dcc 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ParameterClassCheckVisitor.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ParameterClassCheckVisitor.java @@ -43,9 +43,7 @@ class ParameterClassCheckVisitor extends JavaRecursiveElementVisitor{ return; } super.visitMethodCallExpression(expression); - if (isGetClassCall(expression)) { - checked = true; - } else if (isGetInstanceCall(expression)) { + if (isGetClassCall(expression) || isGetInstanceCall(expression)) { checked = true; } } @@ -67,7 +65,7 @@ class ParameterClassCheckVisitor extends JavaRecursiveElementVisitor{ return false; } final String className = aClass.getQualifiedName(); - if (!"java.lang.Class".equals(className)) { + if (!CommonClassNames.JAVA_LANG_CLASS.equals(className)) { return false; } final PsiExpressionList argumentList = @@ -103,7 +101,7 @@ class ParameterClassCheckVisitor extends JavaRecursiveElementVisitor{ return false; } final String className = aClass.getQualifiedName(); - if (!"java.lang.Object".equals(className)) { + if (!CommonClassNames.JAVA_LANG_OBJECT.equals(className)) { return false; } final PsiExpression qualifier = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ReplaceAllDotInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ReplaceAllDotInspection.java index 543dc0e6acc7..285cb1b7d852 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ReplaceAllDotInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ReplaceAllDotInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2006-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,18 +26,21 @@ import org.jetbrains.annotations.NotNull; public class ReplaceAllDotInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "replace.all.dot.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "replace.all.dot.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new SystemSetSecurityManagerVisitor(); } @@ -55,24 +58,26 @@ public class ReplaceAllDotInspection extends BaseInspection { if (!"replaceAll".equals(methodName)) { return; } - final PsiExpressionList argList = expression.getArgumentList(); - final PsiExpression[] args = argList.getExpressions(); - if (args.length != 2) { + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 2) { return; } - final PsiExpression arg = args[0]; - if (!PsiUtil.isConstantExpression(arg)) { + final PsiExpression argument = arguments[0]; + if (!PsiUtil.isConstantExpression(argument)) { return; } - final PsiType argType = arg.getType(); - if (argType == null) { + final PsiType argumentType = argument.getType(); + if (argumentType == null) { return; } - if (!"java.lang.String".equals(argType.getCanonicalText())) { + final String canonicalText = argumentType.getCanonicalText(); + if (!CommonClassNames.JAVA_LANG_STRING.equals(canonicalText)) { return; } final String argValue = - (String) ConstantExpressionUtil.computeCastTo(arg, argType); + (String) ConstantExpressionUtil.computeCastTo(argument, + argumentType); if (!".".equals(argValue)) { return; } @@ -85,7 +90,7 @@ public class ReplaceAllDotInspection extends BaseInspection { return; } final String qualifiedName = containingClass.getQualifiedName(); - if (!"java.lang.String".equals(qualifiedName)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(qualifiedName)) { return; } registerMethodCallError(expression); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/SuspiciousToArrayCallInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/SuspiciousToArrayCallInspection.java index 1a6b096b1d40..8410adc1703a 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/SuspiciousToArrayCallInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/SuspiciousToArrayCallInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2007 Bas Leijdekkers + * Copyright 2005-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,12 +25,14 @@ import org.jetbrains.annotations.NotNull; public class SuspiciousToArrayCallInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "suspicious.to.array.call.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { final PsiType type = (PsiType)infos[0]; @@ -39,10 +41,12 @@ public class SuspiciousToArrayCallInspection extends BaseInspection { type.getPresentableText()); } + @Override public boolean isEnabledByDefault() { return true; } + @Override public BaseInspectionVisitor buildVisitor() { return new SuspiciousToArrayCallVisitor(); } @@ -72,7 +76,8 @@ public class SuspiciousToArrayCallInspection extends BaseInspection { final PsiClassType classType = (PsiClassType)type; final PsiClass aClass = classType.resolve(); if (aClass == null || - !ClassUtils.isSubclass(aClass, "java.util.Collection")) { + !ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_UTIL_COLLECTION)) { return; } final PsiExpressionList argumentList = expression.getArgumentList(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ThrowableInstanceNeverThrownInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ThrowableInstanceNeverThrownInspection.java index 67988706b75a..4bd1070850dd 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ThrowableInstanceNeverThrownInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ThrowableInstanceNeverThrownInspection.java @@ -41,15 +41,16 @@ public class ThrowableInstanceNeverThrownInspection extends BaseInspection { final PsiExpression expression = (PsiExpression)infos[0]; final String type = TypeUtils.expressionHasTypeOrSubtype(expression, - "java.lang.RuntimeException", "java.lang.Exception", - "java.lang.Error"); - if ("java.lang.RuntimeException".equals(type)) { + CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION, + CommonClassNames.JAVA_LANG_EXCEPTION, + CommonClassNames.JAVA_LANG_ERROR); + if (CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION.equals(type)) { return InspectionGadgetsBundle.message( "throwable.instance.never.thrown.runtime.exception.problem.descriptor"); - } else if ("java.lang.Exception".equals(type)) { + } else if (CommonClassNames.JAVA_LANG_EXCEPTION.equals(type)) { return InspectionGadgetsBundle.message( "throwable.instance.never.thrown.checked.exception.problem.descriptor"); - } else if ("java.lang.Error".equals(type)) { + } else if (CommonClassNames.JAVA_LANG_ERROR.equals(type)) { return InspectionGadgetsBundle.message( "throwable.instance.never.thrown.error.problem.descriptor"); } else { @@ -74,7 +75,7 @@ public class ThrowableInstanceNeverThrownInspection extends BaseInspection { @Override public void visitNewExpression(PsiNewExpression expression) { super.visitNewExpression(expression); if (!TypeUtils.expressionHasTypeOrSubtype(expression, - "java.lang.Throwable")) { + CommonClassNames.JAVA_LANG_THROWABLE)) { return; } final PsiElement parent = getParent(expression.getParent()); @@ -183,7 +184,7 @@ public class ThrowableInstanceNeverThrownInspection extends BaseInspection { final PsiParameter[] parameters = parameterList.getParameters(); final PsiType type = parameters[0].getType(); - if (!type.equalsToText("java.lang.Throwable")) { + if (!type.equalsToText(CommonClassNames.JAVA_LANG_THROWABLE)) { return null; } return getParent(methodCallExpression.getParent()); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ThrowableResultOfMethodCallIgnoredInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ThrowableResultOfMethodCallIgnoredInspection.java index 84da57f75758..fc98f3ed36f7 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ThrowableResultOfMethodCallIgnoredInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/ThrowableResultOfMethodCallIgnoredInspection.java @@ -66,7 +66,7 @@ public class ThrowableResultOfMethodCallIgnoredInspection return; } if (!TypeUtils.expressionHasTypeOrSubtype(expression, - "java.lang.Throwable")) { + CommonClassNames.JAVA_LANG_THROWABLE)) { return; } final PsiMethod method = expression.resolveMethod(); @@ -76,7 +76,7 @@ public class ThrowableResultOfMethodCallIgnoredInspection if (!method.hasModifierProperty(PsiModifier.STATIC)) { final PsiClass containingClass = method.getContainingClass(); if (ClassUtils.isSubclass(containingClass, - "java.lang.Throwable")) { + CommonClassNames.JAVA_LANG_THROWABLE)) { return; } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/UseOfPropertiesAsHashtableInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/UseOfPropertiesAsHashtableInspection.java index 3bac60cb7daf..37dc74eb8c17 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/UseOfPropertiesAsHashtableInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/UseOfPropertiesAsHashtableInspection.java @@ -26,18 +26,21 @@ import org.jetbrains.annotations.NotNull; public class UseOfPropertiesAsHashtableInspection extends BaseInspection { + @Override @NotNull public String getDisplayName(){ return InspectionGadgetsBundle.message( "properties.object.as.hashtable.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos){ return InspectionGadgetsBundle.message( "properties.object.as.hashtable.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor(){ return new SystemSetSecurityManagerVisitor(); } @@ -71,7 +74,7 @@ public class UseOfPropertiesAsHashtableInspection extends BaseInspection { return; } if(!TypeUtils.expressionHasTypeOrSubtype(qualifier, - "java.util.Properties")){ + CommonClassNames.JAVA_UTIL_PROPERTIES)){ return; } registerMethodCallError(expression); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/MissingDeprecatedAnnotationInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/MissingDeprecatedAnnotationInspection.java index 4194daa955f0..2110bb8a8fcc 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/MissingDeprecatedAnnotationInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/MissingDeprecatedAnnotationInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,18 +30,21 @@ import org.jetbrains.annotations.NotNull; public class MissingDeprecatedAnnotationInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "missing.deprecated.annotation.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "missing.deprecated.annotation.problem.descriptor"); } + @Override protected InspectionGadgetsFix buildFix(Object... infos) { return new MissingDeprecatedAnnotationFix(); } @@ -55,15 +58,15 @@ public class MissingDeprecatedAnnotationInspection extends BaseInspection { "missing.deprecated.annotation.add.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { - final PsiElement identifier = descriptor.getPsiElement(); final PsiModifierListOwner parent = (PsiModifierListOwner)identifier.getParent(); assert parent != null; - final PsiManager psiManager = parent.getManager(); - final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); + final PsiElementFactory factory = + JavaPsiFacade.getElementFactory(project); final PsiAnnotation annotation = factory.createAnnotationFromText("@java.lang.Deprecated", parent); @@ -75,6 +78,7 @@ public class MissingDeprecatedAnnotationInspection extends BaseInspection { } } + @Override public BaseInspectionVisitor buildVisitor() { return new MissingDeprecatedAnnotationVisitor(); } @@ -132,7 +136,8 @@ public class MissingDeprecatedAnnotationInspection extends BaseInspection { return false; } final PsiAnnotation annotation = - modifierList.findAnnotation("java.lang.Deprecated"); + modifierList.findAnnotation( + CommonClassNames.JAVA_LANG_DEPRECATED); return annotation != null; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/SingletonInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/SingletonInspection.java index ef73360935f9..683f9bbe4092 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/SingletonInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/SingletonInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,16 +24,24 @@ import org.jetbrains.annotations.NotNull; public class SingletonInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message("singleton.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message("singleton.problem.descriptor"); } + @Override + public boolean runForWholeFile() { + return true; + } + + @Override public BaseInspectionVisitor buildVisitor() { return new SingletonVisitor(); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/ForLoopWithMissingComponentInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/ForLoopWithMissingComponentInspection.java index cfb67296eecc..1930bd65fc85 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/ForLoopWithMissingComponentInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/ForLoopWithMissingComponentInspection.java @@ -146,7 +146,7 @@ public class ForLoopWithMissingComponentInspection extends BaseInspection { if(declaredClass == null){ return false; } - if(!ClassUtils.isSubclass(declaredClass, "java.util.Iterator")){ + if(!ClassUtils.isSubclass(declaredClass, CommonClassNames.JAVA_UTIL_ITERATOR)){ return false; } final PsiExpression initialValue = variable.getInitializer(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/PointlessBooleanExpressionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/PointlessBooleanExpressionInspection.java index 0bf056e2f1bb..ecd3197e2742 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/PointlessBooleanExpressionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/PointlessBooleanExpressionInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,6 +54,7 @@ public class PointlessBooleanExpressionInspection extends BaseInspection { /** @noinspection PublicField*/ public boolean m_ignoreExpressionsContainingConstants = false; + @Override public JComponent createOptionsPanel(){ return new SingleCheckboxOptionsPanel( InspectionGadgetsBundle.message( @@ -61,16 +62,19 @@ public class PointlessBooleanExpressionInspection extends BaseInspection { this, "m_ignoreExpressionsContainingConstants"); } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "pointless.boolean.expression.display.name"); } + @Override public boolean isEnabledByDefault(){ return true; } + @Override @NotNull public String buildErrorString(Object... infos){ if(infos[0] instanceof PsiBinaryExpression){ @@ -88,6 +92,7 @@ public class PointlessBooleanExpressionInspection extends BaseInspection { } } + @Override public BaseInspectionVisitor buildVisitor(){ return new PointlessBooleanExpressionVisitor(); } @@ -176,6 +181,7 @@ public class PointlessBooleanExpressionInspection extends BaseInspection { } } + @Override public InspectionGadgetsFix buildFix(Object... infos){ return new BooleanLiteralComparisonFix(); } @@ -188,6 +194,7 @@ public class PointlessBooleanExpressionInspection extends BaseInspection { "constant.conditional.expression.simplify.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException{ final PsiElement element = descriptor.getPsiElement(); @@ -236,7 +243,8 @@ public class PointlessBooleanExpressionInspection extends BaseInspection { return; } if(!rhsType.equals(PsiType.BOOLEAN)&& - !rhsType.equalsToText("java.lang.Boolean")){ + !rhsType.equalsToText( + CommonClassNames.JAVA_LANG_BOOLEAN)){ return; } final PsiExpression lhs = expression.getLOperand(); @@ -245,7 +253,8 @@ public class PointlessBooleanExpressionInspection extends BaseInspection { return; } if(!lhsType.equals(PsiType.BOOLEAN) && - !lhsType.equalsToText("java.lang.Boolean")){ + !lhsType.equalsToText( + CommonClassNames.JAVA_LANG_BOOLEAN)){ return; } final IElementType tokenType = sign.getTokenType(); @@ -319,7 +328,7 @@ public class PointlessBooleanExpressionInspection extends BaseInspection { final Boolean value = (Boolean) ConstantExpressionUtil.computeCastTo(expression, PsiType.BOOLEAN); - return value != null && value; + return value != null && value.booleanValue(); } private boolean isFalse(PsiExpression expression){ @@ -333,6 +342,6 @@ public class PointlessBooleanExpressionInspection extends BaseInspection { final Boolean value = (Boolean) ConstantExpressionUtil.computeCastTo(expression, PsiType.BOOLEAN); - return value != null && !value; + return value != null && !value.booleanValue(); } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/encapsulation/ReturnOfCollectionFieldInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/encapsulation/ReturnOfCollectionFieldInspection.java index 97f86806de0b..a723171b2e16 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/encapsulation/ReturnOfCollectionFieldInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/encapsulation/ReturnOfCollectionFieldInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.psiutils.CollectionUtils; import com.siyeh.ig.psiutils.TypeUtils; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -37,17 +38,20 @@ public class ReturnOfCollectionFieldInspection extends BaseInspection{ /** @noinspection PublicField*/ public boolean ignorePrivateMethods = true; + @Override @NotNull public String getID(){ return "ReturnOfCollectionOrArrayField"; } + @Override @NotNull public String getDisplayName(){ return InspectionGadgetsBundle.message( "return.of.collection.array.field.display.name"); } + @Override @Nullable public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel( @@ -56,6 +60,7 @@ public class ReturnOfCollectionFieldInspection extends BaseInspection{ "ignorePrivateMethods"); } + @Override @NotNull public String buildErrorString(Object... infos){ final PsiField field = (PsiField)infos[0]; @@ -69,13 +74,14 @@ public class ReturnOfCollectionFieldInspection extends BaseInspection{ } } + @Override @Nullable protected InspectionGadgetsFix buildFix(Object... infos) { final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) infos[1]; final String text = referenceExpression.getText(); if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, - "java.util.Map")) { + CommonClassNames.JAVA_UTIL_MAP)) { if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, "java.util.SortedMap")) { return new ReturnOfCollectionFieldFix( @@ -85,9 +91,9 @@ public class ReturnOfCollectionFieldInspection extends BaseInspection{ return new ReturnOfCollectionFieldFix( "java.util.Collections.unmodifiableMap(" + text + ')'); } else if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, - "java.util.Collection")) { + CommonClassNames.JAVA_UTIL_COLLECTION)) { if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, - "java.util.Set")) { + CommonClassNames.JAVA_UTIL_SET)) { if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, "java.util.SortedSet")) { return new ReturnOfCollectionFieldFix( @@ -97,7 +103,7 @@ public class ReturnOfCollectionFieldInspection extends BaseInspection{ return new ReturnOfCollectionFieldFix( "java.util.Collections.unmodifiableSet(" + text + ')'); } else if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, - "java.util.List")) { + CommonClassNames.JAVA_UTIL_LIST)) { return new ReturnOfCollectionFieldFix( "java.util.Collections.unmodifiableList(" + text + ')'); } @@ -108,6 +114,7 @@ public class ReturnOfCollectionFieldInspection extends BaseInspection{ return null; } + @Override public BaseInspectionVisitor buildVisitor(){ return new ReturnOfCollectionFieldVisitor(); } @@ -117,7 +124,7 @@ public class ReturnOfCollectionFieldInspection extends BaseInspection{ private final String replacementText; - ReturnOfCollectionFieldFix(String replacementText) { + ReturnOfCollectionFieldFix(@NonNls String replacementText) { this.replacementText = replacementText; } @@ -127,6 +134,7 @@ public class ReturnOfCollectionFieldInspection extends BaseInspection{ "return.of.collection.field.quickfix", replacementText); } + @Override protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/encapsulation/ReturnOfDateFieldInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/encapsulation/ReturnOfDateFieldInspection.java index 20c34ec4d492..c01e691f19c8 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/encapsulation/ReturnOfDateFieldInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/encapsulation/ReturnOfDateFieldInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,8 @@ public class ReturnOfDateFieldInspection extends BaseInspection{ return; } final String type = TypeUtils.expressionHasTypeOrSubtype( - returnValue, "java.util.Date", "java.util.Calendar"); + returnValue, CommonClassNames.JAVA_UTIL_DATE, + CommonClassNames.JAVA_UTIL_CALENDAR); if (type == null) { return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/CheckedExceptionClassInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/CheckedExceptionClassInspection.java index f95fac31882b..7cd6b3e43d57 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/CheckedExceptionClassInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/CheckedExceptionClassInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.errorhandling; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; @@ -24,18 +25,21 @@ import org.jetbrains.annotations.NotNull; public class CheckedExceptionClassInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "checked.exception.class.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "checked.exception.class.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new CheckedExceptionClassVisitor(); } @@ -43,10 +47,12 @@ public class CheckedExceptionClassInspection extends BaseInspection { private static class CheckedExceptionClassVisitor extends BaseInspectionVisitor { @Override public void visitClass(@NotNull PsiClass aClass) { - if (!ClassUtils.isSubclass(aClass, "java.lang.Throwable")) { + if (!ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_LANG_THROWABLE)) { return; } - if (ClassUtils.isSubclass(aClass, "java.lang.RuntimeException")) { + if (ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION)) { return; } registerClassError(aClass); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/ErrorRethrownInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/ErrorRethrownInspection.java index bfd37fcdaef0..79377f6cb729 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/ErrorRethrownInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/ErrorRethrownInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,22 +26,26 @@ import org.jetbrains.annotations.NotNull; public class ErrorRethrownInspection extends BaseInspection { + @Override @NotNull public String getID() { return "ErrorNotRethrown"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message("error.rethrown.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "error.rethrown.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new ErrorRethrownVisitor(); } @@ -69,7 +73,8 @@ public class ErrorRethrownInspection extends BaseInspection { if (aClass == null) { return; } - if (!ClassUtils.isSubclass(aClass, "java.lang.Error")) { + if (!ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_LANG_ERROR)) { return; } if (TypeUtils.typeEquals("java.lang.ThreadDeath", type)) { diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/NonFinalFieldOfExceptionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/NonFinalFieldOfExceptionInspection.java index 96b50cb3ab39..3cbe78119b15 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/NonFinalFieldOfExceptionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/NonFinalFieldOfExceptionInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.errorhandling; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiField; import com.intellij.psi.PsiModifier; @@ -29,24 +30,28 @@ import org.jetbrains.annotations.Nullable; public class NonFinalFieldOfExceptionInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "non.final.field.of.exception.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "non.final.field.of.exception.problem.descriptor"); } + @Override @Nullable protected InspectionGadgetsFix buildFix(Object... infos) { final PsiField field = (PsiField) infos[0]; return MakeFieldFinalFix.buildFix(field); } + @Override public BaseInspectionVisitor buildVisitor() { return new NonFinalFieldOfExceptionVisitor(); } @@ -65,7 +70,7 @@ public class NonFinalFieldOfExceptionInspection extends BaseInspection { return; } if (!ClassUtils.isSubclass(containingClass, - "java.lang.Exception")) { + CommonClassNames.JAVA_LANG_EXCEPTION)) { return; } registerFieldError(field, field); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/TooBroadCatchInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/TooBroadCatchInspection.java index 0010735df6fc..6a748496860e 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/TooBroadCatchInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/TooBroadCatchInspection.java @@ -191,7 +191,7 @@ public class TooBroadCatchInspection extends BaseInspection { if (tryBlock == null) { return; } - final Set exceptionsThrown = + final Set exceptionsThrown = ExceptionUtils.calculateExceptionsThrown(tryBlock); final int numExceptionsThrown = exceptionsThrown.size(); final Set exceptionsCaught = @@ -212,11 +212,11 @@ public class TooBroadCatchInspection extends BaseInspection { if (exceptionsThrown.contains(typeCaught)) { exceptionsCaught.add(typeCaught); } - final List typesMasked = new ArrayList(); - for (PsiClassType typeThrown : exceptionsThrown) { + final List typesMasked = new ArrayList(); + for (PsiType typeThrown : exceptionsThrown) { if (!exceptionsCaught.contains(typeThrown) && typeCaught.isAssignableFrom(typeThrown)) { - exceptionsCaught.add(typeCaught); + exceptionsCaught.add(typeThrown); typesMasked.add(typeThrown); } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/UncheckedExceptionClassInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/UncheckedExceptionClassInspection.java index 2d40ac34a829..b6469ffe0b1b 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/UncheckedExceptionClassInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/errorhandling/UncheckedExceptionClassInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.errorhandling; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; @@ -24,18 +25,21 @@ import org.jetbrains.annotations.NotNull; public class UncheckedExceptionClassInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "unchecked.exception.class.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "unchecked.exception.class.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new UncheckedExceptionClassVisitor(); } @@ -44,11 +48,14 @@ public class UncheckedExceptionClassInspection extends BaseInspection { extends BaseInspectionVisitor { @Override public void visitClass(@NotNull PsiClass aClass) { - if (!ClassUtils.isSubclass(aClass, "java.lang.Throwable")) { + if (!ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_LANG_THROWABLE)) { return; } - if (ClassUtils.isSubclass(aClass, "java.lang.Exception") && - !ClassUtils.isSubclass(aClass, "java.lang.RuntimeException")) { + if (ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_LANG_EXCEPTION) && + !ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION)) { return; } registerClassError(aClass); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/finalization/FinalizeCallsSuperFinalizeInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/finalization/FinalizeCallsSuperFinalizeInspection.java index 117b9728420d..cca497b0373b 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/finalization/FinalizeCallsSuperFinalizeInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/finalization/FinalizeCallsSuperFinalizeInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,27 +34,32 @@ public class FinalizeCallsSuperFinalizeInspection extends BaseInspection { @SuppressWarnings("PublicField") public boolean ignoreTrivialFinalizers = true; + @Override @NotNull public String getID(){ return "FinalizeDoesntCallSuperFinalize"; } + @Override @NotNull public String getDisplayName(){ return InspectionGadgetsBundle.message( "finalize.doesnt.call.super.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos){ return InspectionGadgetsBundle.message( "finalize.doesnt.call.super.problem.descriptor"); } + @Override public boolean isEnabledByDefault(){ return true; } + @Override public JComponent createOptionsPanel(){ final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this); @@ -62,10 +67,12 @@ public class FinalizeCallsSuperFinalizeInspection extends BaseInspection { "finalize.doesnt.call.super.ignore.option"), "ignoreObjectSubclasses"); optionsPanel.addCheckbox(InspectionGadgetsBundle.message( - "ignore.trivial.finalizers.option"), "ignoreTrivialFinalizers"); + "ignore.trivial.finalizers.option"), + "ignoreTrivialFinalizers"); return optionsPanel; } + @Override public BaseInspectionVisitor buildVisitor(){ return new NoExplicitFinalizeCallsVisitor(); } @@ -90,7 +97,7 @@ public class FinalizeCallsSuperFinalizeInspection extends BaseInspection { final PsiClass superClass = containingClass.getSuperClass(); if(superClass != null){ final String superClassName = superClass.getQualifiedName(); - if("java.lang.Object".equals(superClassName)){ + if(CommonClassNames.JAVA_LANG_OBJECT.equals(superClassName)){ return; } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeCloneableFix.java b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeCloneableFix.java index f1eebd14cda8..30fd8e1e4139 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeCloneableFix.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeCloneableFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2005 Dave Griffith + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,23 +26,32 @@ import com.siyeh.ig.psiutils.ClassUtils; import org.jetbrains.annotations.NotNull; public class MakeCloneableFix extends InspectionGadgetsFix { + @NotNull public String getName() { return InspectionGadgetsBundle.message("make.cloneable.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) - throws IncorrectOperationException{ + throws IncorrectOperationException{ final PsiElement nameElement = descriptor.getPsiElement(); - final PsiClass containingClass = ClassUtils.getContainingClass(nameElement); - assert containingClass != null; - final PsiManager psiManager = containingClass.getManager(); - final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); + final PsiClass containingClass = + ClassUtils.getContainingClass(nameElement); + if (containingClass == null) { + return; + } + final PsiElementFactory elementFactory = + JavaPsiFacade.getElementFactory(project); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); - final PsiJavaCodeReferenceElement ref = elementFactory.createReferenceElementByFQClassName("java.lang.Cloneable", scope); - final PsiReferenceList implementsList = containingClass.getImplementsList(); - assert implementsList != null; - implementsList.add(ref); - + final PsiJavaCodeReferenceElement ref = + elementFactory.createReferenceElementByFQClassName( + CommonClassNames.JAVA_LANG_CLONEABLE, scope); + final PsiReferenceList implementsList = + containingClass.getImplementsList(); + if (implementsList == null) { + return; + } + implementsList.add(ref); } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeSerializableFix.java b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeSerializableFix.java index 0198bfcb20d9..7135e78a817e 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeSerializableFix.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MakeSerializableFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,18 +33,19 @@ public class MakeSerializableFix extends InspectionGadgetsFix{ "make.class.serializable.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException{ final PsiElement nameElement = descriptor.getPsiElement(); final PsiClass containingClass = ClassUtils.getContainingClass(nameElement); assert containingClass != null; - final PsiManager psiManager = containingClass.getManager(); - final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); + final PsiElementFactory elementFactory = + JavaPsiFacade.getElementFactory(project); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiJavaCodeReferenceElement referenceElement = elementFactory.createReferenceElementByFQClassName( - "java.io.Serializable", scope); + CommonClassNames.JAVA_IO_SERIALIZABLE, scope); final PsiReferenceList implementsList = containingClass.getImplementsList(); assert implementsList != null; diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MemberSignature.java b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MemberSignature.java index e9a24bbe1411..4241e991fbe3 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MemberSignature.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/MemberSignature.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2006 Bas Leijdekkers + * Copyright 2003-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -237,7 +237,7 @@ public class MemberSignature implements Comparable if(qualifiedName == null) { // for type parameters - buffer.append("java.lang.Object"); + buffer.append(CommonClassNames.JAVA_LANG_OBJECT); } else { diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/SerialVersionUIDBuilder.java b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/SerialVersionUIDBuilder.java index 8c1e7aec53fb..3ad54aaec625 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/SerialVersionUIDBuilder.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/fixes/SerialVersionUIDBuilder.java @@ -37,8 +37,6 @@ public class SerialVersionUIDBuilder extends JavaRecursiveElementVisitor{ @NonNls private static final String ACCESS_METHOD_NAME_PREFIX = "access$"; - private static final String SERIALIZABLE_CLASS_NAME = "java.io.Serializable"; - private final PsiClass clazz; private int index = -1; private final Set nonPrivateConstructors; @@ -156,7 +154,9 @@ public class SerialVersionUIDBuilder extends JavaRecursiveElementVisitor{ public static long computeDefaultSUID(PsiClass psiClass) { final Project project = psiClass.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); - final PsiClass serializable = JavaPsiFacade.getInstance(project).findClass(SERIALIZABLE_CLASS_NAME, scope); + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); + final PsiClass serializable = + psiFacade.findClass(CommonClassNames.JAVA_IO_SERIALIZABLE, scope); if (serializable == null) { // no jdk defined for project. return -1L; diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/AbstractClassExtendsConcreteClassInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/AbstractClassExtendsConcreteClassInspection.java index e0722afd379b..8ba6bc3db293 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/AbstractClassExtendsConcreteClassInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/AbstractClassExtendsConcreteClassInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.inheritance; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiModifier; import com.siyeh.InspectionGadgetsBundle; @@ -25,18 +26,21 @@ import org.jetbrains.annotations.NotNull; public class AbstractClassExtendsConcreteClassInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "abstract.class.extends.concrete.class.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "abstract.class.extends.concrete.class.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new AbstractClassExtendsConcreteClassVisitor(); } @@ -60,7 +64,7 @@ public class AbstractClassExtendsConcreteClassInspection return; } final String superclassName = superClass.getQualifiedName(); - if ("java.lang.Object".equals(superclassName)) { + if (CommonClassNames.JAVA_LANG_OBJECT.equals(superclassName)) { return; } registerClassError(aClass); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/AbstractMethodOverridesConcreteMethodInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/AbstractMethodOverridesConcreteMethodInspection.java index 3483e0101b3c..b55fda9cd714 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/AbstractMethodOverridesConcreteMethodInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/AbstractMethodOverridesConcreteMethodInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.inheritance; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiModifier; @@ -26,18 +27,21 @@ import org.jetbrains.annotations.NotNull; public class AbstractMethodOverridesConcreteMethodInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "abstract.method.overrides.concrete.method.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "abstract.method.overrides.concrete.method.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new AbstractMethodOverridesConcreteMethodVisitor(); } @@ -69,7 +73,7 @@ public class AbstractMethodOverridesConcreteMethodInspection } final String superClassName = superClass.getQualifiedName(); if (!superClass.isInterface() && - !"java.lang.Object".equals(superClassName) && + !CommonClassNames.JAVA_LANG_OBJECT.equals(superClassName) && !superMethod.hasModifierProperty(PsiModifier.ABSTRACT)) { registerMethodError(method); return; diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/RefusedBequestInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/RefusedBequestInspection.java index 6fe7ab96a31b..dda7193b26c8 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/RefusedBequestInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/inheritance/RefusedBequestInspection.java @@ -80,7 +80,7 @@ public class RefusedBequestInspection extends BaseInspection { return; } final String className = containingClass.getQualifiedName(); - if("java.lang.Object".equals(className)){ + if(CommonClassNames.JAVA_LANG_OBJECT.equals(className)){ return; } if (ignoreEmptySuperMethods){ diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/CharacterComparisonInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/CharacterComparisonInspection.java index d62d2fe05212..1c9a6e564e1c 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/CharacterComparisonInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/CharacterComparisonInspection.java @@ -15,6 +15,7 @@ */ package com.siyeh.ig.internationalization; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiBinaryExpression; import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiKeyword; @@ -84,7 +85,8 @@ public class CharacterComparisonInspection extends BaseInspection { private static boolean isCharacter(PsiExpression expression) { return TypeUtils.expressionHasType(expression, PsiKeyword.CHAR) || - TypeUtils.expressionHasType(expression, "java.lang.Character"); + TypeUtils.expressionHasType(expression, + CommonClassNames.JAVA_LANG_CHARACTER); } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/DateToStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/DateToStringInspection.java index 8617639ecd2f..cd10da93bcfd 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/DateToStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/DateToStringInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.internationalization; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiExpressionList; import com.intellij.psi.PsiMethodCallExpression; import com.intellij.psi.PsiType; @@ -28,23 +29,27 @@ import org.jetbrains.annotations.NotNull; public class DateToStringInspection extends BaseInspection { + @Override @NotNull public String getID() { return "CallToDateToString"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "call.to.date.tostring.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "call.to.date.tostring.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new DateToStringVisitor(); } @@ -59,7 +64,8 @@ public class DateToStringInspection extends BaseInspection { return; } final PsiType targetType = MethodCallUtils.getTargetType(expression); - if (!TypeUtils.typeEquals("java.util.Date", targetType)) { + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_UTIL_DATE, + targetType)) { return; } final PsiExpressionList argumentList = expression.getArgumentList(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringCompareToInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringCompareToInspection.java index d8ba882b74ad..da3253ac84b8 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringCompareToInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringCompareToInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,23 +33,27 @@ import java.util.List; public class StringCompareToInspection extends BaseInspection { + @Override @NotNull public String getID() { return "CallToStringCompareTo"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "string.compareto.call.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "string.compareto.call.problem.descriptor"); } + @Override @NotNull protected InspectionGadgetsFix[] buildFixes(Object... infos) { final PsiMethodCallExpression methodCallExpression = @@ -78,6 +82,7 @@ public class StringCompareToInspection extends BaseInspection { return result.toArray(new InspectionGadgetsFix[result.size()]); } + @Override public BaseInspectionVisitor buildVisitor() { return new StringCompareToVisitor(); } @@ -135,7 +140,7 @@ public class StringCompareToInspection extends BaseInspection { return false; } final String className = aClass.getQualifiedName(); - return "java.lang.String".equals(className); + return CommonClassNames.JAVA_LANG_STRING.equals(className); } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringEqualsIgnoreCaseInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringEqualsIgnoreCaseInspection.java index 20063ebcb7dc..8d29c1101d89 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringEqualsIgnoreCaseInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringEqualsIgnoreCaseInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,23 +32,27 @@ import java.util.List; public class StringEqualsIgnoreCaseInspection extends BaseInspection { + @Override @NotNull public String getID(){ return "CallToStringEqualsIgnoreCase"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "string.equalsignorecase.call.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "string.equalsignorecase.call.problem.descriptor"); } + @Override @NotNull protected InspectionGadgetsFix[] buildFixes(Object... infos) { final PsiMethodCallExpression methodCallExpression = @@ -76,6 +80,7 @@ public class StringEqualsIgnoreCaseInspection extends BaseInspection { return result.toArray(new InspectionGadgetsFix[result.size()]); } + @Override public BaseInspectionVisitor buildVisitor() { return new StringEqualsIgnoreCaseVisitor(); } @@ -111,7 +116,7 @@ public class StringEqualsIgnoreCaseInspection extends BaseInspection { return; } final String className = aClass.getQualifiedName(); - if (!"java.lang.String".equals(className)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { return; } final PsiExpression qualifier = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringEqualsInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringEqualsInspection.java index 6a5e8327515f..de07a2b88775 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringEqualsInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringEqualsInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,23 +32,27 @@ import java.util.List; public class StringEqualsInspection extends BaseInspection { + @Override @NotNull public String getID() { return "CallToStringEquals"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "string.equals.call.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "string.equals.call.problem.descriptor"); } + @Override @NotNull protected InspectionGadgetsFix[] buildFixes(Object... infos) { final PsiMethodCallExpression methodCallExpression = @@ -77,6 +81,7 @@ public class StringEqualsInspection extends BaseInspection { return result.toArray(new InspectionGadgetsFix[result.size()]); } + @Override public BaseInspectionVisitor buildVisitor() { return new StringEqualsVisitor(); } @@ -104,7 +109,7 @@ public class StringEqualsInspection extends BaseInspection { return; } final String className = aClass.getQualifiedName(); - if (!"java.lang.String".equals(className)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { return; } final PsiReferenceExpression methodExpression = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringToUpperWithoutLocaleInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringToUpperWithoutLocaleInspection.java index f439520aa327..f1838ebcacba 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringToUpperWithoutLocaleInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/internationalization/StringToUpperWithoutLocaleInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,23 +29,27 @@ import org.jetbrains.annotations.Nullable; public class StringToUpperWithoutLocaleInspection extends BaseInspection { + @Override @NotNull public String getID(){ return "StringToUpperCaseOrToLowerCaseWithoutLocale"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "string.touppercase.tolowercase.without.locale.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "string.touppercase.tolowercase.without.locale.problem.descriptor"); } + @Override @Nullable protected InspectionGadgetsFix buildFix(Object... infos) { final PsiReferenceExpression methodExpression = @@ -60,6 +64,7 @@ public class StringToUpperWithoutLocaleInspection extends BaseInspection { AnnotationUtil.NON_NLS, annotatableQualifier)); } + @Override public BaseInspectionVisitor buildVisitor() { return new StringToUpperWithoutLocaleVisitor(); } @@ -93,7 +98,7 @@ public class StringToUpperWithoutLocaleInspection extends BaseInspection { return; } final String className = containingClass.getQualifiedName(); - if(!"java.lang.String".equals(className)) { + if(!CommonClassNames.JAVA_LANG_STRING.equals(className)) { return; } final PsiExpression qualifier = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/AutoBoxingInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/AutoBoxingInspection.java index 71a5cd489ba6..4b81ae147025 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/AutoBoxingInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/AutoBoxingInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,14 +48,14 @@ public class AutoBoxingInspection extends BaseInspection { new HashMap(8); static { - s_boxingClasses.put("byte", "java.lang.Byte"); - s_boxingClasses.put("short", "java.lang.Short"); - s_boxingClasses.put("int", "java.lang.Integer"); - s_boxingClasses.put("long", "java.lang.Long"); - s_boxingClasses.put("float", "java.lang.Float"); - s_boxingClasses.put("double", "java.lang.Double"); - s_boxingClasses.put("boolean", "java.lang.Boolean"); - s_boxingClasses.put("char", "java.lang.Character"); + s_boxingClasses.put("byte", CommonClassNames.JAVA_LANG_BYTE); + s_boxingClasses.put("short", CommonClassNames.JAVA_LANG_SHORT); + s_boxingClasses.put("int", CommonClassNames.JAVA_LANG_INTEGER); + s_boxingClasses.put("long", CommonClassNames.JAVA_LANG_LONG); + s_boxingClasses.put("float", CommonClassNames.JAVA_LANG_FLOAT); + s_boxingClasses.put("double", CommonClassNames.JAVA_LANG_DOUBLE); + s_boxingClasses.put("boolean", CommonClassNames.JAVA_LANG_BOOLEAN); + s_boxingClasses.put("char", CommonClassNames.JAVA_LANG_CHARACTER); } @Override @@ -256,7 +256,8 @@ public class AutoBoxingInspection extends BaseInspection { (PsiMethodCallExpression)grandParent; final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); + @NonNls final String methodName = + methodExpression.getReferenceName(); if (!"put".equals(methodName) && !"set".equals(methodName) && !"add".equals(methodName)) { return false; @@ -264,7 +265,8 @@ public class AutoBoxingInspection extends BaseInspection { final PsiExpression qualifier = methodExpression.getQualifierExpression(); return TypeUtils.expressionHasTypeOrSubtype(qualifier, - "java.util.Collection", "java.util.Map") != null; + CommonClassNames.JAVA_UTIL_COLLECTION, + CommonClassNames.JAVA_UTIL_MAP) != null; } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/AutoUnboxingInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/AutoUnboxingInspection.java index 81b6554a5a29..85ea280bcebe 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/AutoUnboxingInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/AutoUnboxingInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -252,11 +252,14 @@ public class AutoUnboxingInspection extends BaseInspection { } final PsiField field = (PsiField) target; final PsiClass containingClass = field.getContainingClass(); - final String qualifiedName = containingClass.getQualifiedName(); - if (!"java.lang.Boolean".equals(qualifiedName)) { + if (containingClass == null) { return null; } - final String name = field.getName(); + final String qualifiedName = containingClass.getQualifiedName(); + if (!CommonClassNames.JAVA_LANG_BOOLEAN.equals(qualifiedName)) { + return null; + } + @NonNls final String name = field.getName(); if ("TRUE".equals(name)) { return "true"; } else if ("FALSE".equals(name)) { diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/EnumerationCanBeIterationInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/EnumerationCanBeIterationInspection.java index 6b8a01f72bd7..19a715a24013 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/EnumerationCanBeIterationInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk/EnumerationCanBeIterationInspection.java @@ -187,7 +187,7 @@ public class EnumerationCanBeIterationInspection extends BaseInspection { if (codeStyleSettings.GENERATE_FINAL_LOCALS) { newStatementText.append("final "); } - newStatementText.append("java.util.Iterator"); + newStatementText.append(CommonClassNames.JAVA_UTIL_ITERATOR); if (parameterType != null) { final String typeText = parameterType.getCanonicalText(); newStatementText.append('<'); @@ -318,7 +318,7 @@ public class EnumerationCanBeIterationInspection extends BaseInspection { final PsiElementFactory factory = facade.getElementFactory(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiClass iteratorClass = - facade.findClass("java.util.Iterator", scope); + facade.findClass(CommonClassNames.JAVA_UTIL_ITERATOR, scope); if (iteratorClass == null) { return "iterator"; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/CollectionsFieldAccessReplaceableByMethodCallInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/CollectionsFieldAccessReplaceableByMethodCallInspection.java index f4cdc1c926d5..dda2605db29e 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/CollectionsFieldAccessReplaceableByMethodCallInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/CollectionsFieldAccessReplaceableByMethodCallInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Bas Leijdekkers + * Copyright 2008-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,18 +27,21 @@ import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.psiutils.ExpectedTypeUtils; import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class CollectionsFieldAccessReplaceableByMethodCallInspection extends BaseInspection { + @Override @Nls @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "collections.field.access.replaceable.by.method.call.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( @@ -46,6 +49,7 @@ public class CollectionsFieldAccessReplaceableByMethodCallInspection infos[1]); } + @Override @Nullable protected InspectionGadgetsFix buildFix(Object... infos) { final PsiReferenceExpression expression = @@ -59,7 +63,8 @@ public class CollectionsFieldAccessReplaceableByMethodCallInspection private final String replacementText; - private CollectionsFieldAccessReplaceableByMethodCallFix(String referenceName) { + private CollectionsFieldAccessReplaceableByMethodCallFix( + String referenceName) { replacementText = getCollectionsMethodCallText(referenceName); } @@ -70,6 +75,7 @@ public class CollectionsFieldAccessReplaceableByMethodCallInspection replacementText); } + @NonNls private static String getCollectionsMethodCallText( PsiReferenceExpression referenceExpression) { final String referenceName = referenceExpression.getReferenceName(); @@ -77,35 +83,42 @@ public class CollectionsFieldAccessReplaceableByMethodCallInspection if (!(parent instanceof PsiExpressionList)) { return getUntypedCollectionsMethodCallText(referenceName); } - final PsiType type = ExpectedTypeUtils.findExpectedType(referenceExpression, false); + final PsiType type = ExpectedTypeUtils.findExpectedType( + referenceExpression, false); if (!(type instanceof PsiClassType)) { return getUntypedCollectionsMethodCallText(referenceName); } final PsiClassType classType = (PsiClassType) type; final PsiType[] parameterTypes = classType.getParameters(); boolean useTypeParameter = false; - String[] canonicalTexts = new String[parameterTypes.length]; + final String[] canonicalTexts = new String[parameterTypes.length]; for (int i = 0, parameterTypesLength = parameterTypes.length; i < parameterTypesLength; i++) { final PsiType parameterType = parameterTypes[i]; - if (!parameterType.equalsToText("java.lang.Object")) { + if (!parameterType.equalsToText( + CommonClassNames.JAVA_LANG_OBJECT)) { useTypeParameter = true; } canonicalTexts[i] = parameterType.getCanonicalText(); } if (useTypeParameter) { - return "Collections.<" + StringUtil.join(canonicalTexts, ",") + ">" + + return "Collections.<" + StringUtil.join(canonicalTexts, ",") + + '>' + getCollectionsMethodCallText(referenceName); } else { return getUntypedCollectionsMethodCallText(referenceName); } } - private static String getUntypedCollectionsMethodCallText(String referenceName) { + @NonNls + private static String getUntypedCollectionsMethodCallText( + String referenceName) { return "Collections." + getCollectionsMethodCallText(referenceName); } - private static String getCollectionsMethodCallText(String referenceName) { + @NonNls + private static String getCollectionsMethodCallText( + @NonNls String referenceName) { if ("EMPTY_LIST".equals(referenceName)) { return "emptyList()"; } else if ("EMPTY_MAP".equals(referenceName)) { @@ -118,18 +131,23 @@ public class CollectionsFieldAccessReplaceableByMethodCallInspection } } + @Override protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); if (!(element instanceof PsiReferenceExpression)) { return; } - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) element; - final String newMethodCallText = getCollectionsMethodCallText(referenceExpression); - replaceExpression(referenceExpression, "java.util." + newMethodCallText); + final PsiReferenceExpression referenceExpression = + (PsiReferenceExpression) element; + final String newMethodCallText = + getCollectionsMethodCallText(referenceExpression); + replaceExpression(referenceExpression, + "java.util." + newMethodCallText); } } + @Override public BaseInspectionVisitor buildVisitor() { return new CollectionsFieldAccessReplaceableByMethodCallVisitor(); } @@ -144,8 +162,8 @@ public class CollectionsFieldAccessReplaceableByMethodCallInspection return; } super.visitReferenceExpression(expression); - final String name = expression.getReferenceName(); - final String replacement; + @NonNls final String name = expression.getReferenceName(); + @NonNls final String replacement; if ("EMPTY_LIST".equals(name)) { replacement = "emptyList()"; } else if ("EMPTY_MAP".equals(name)) { @@ -165,7 +183,7 @@ public class CollectionsFieldAccessReplaceableByMethodCallInspection return; } final String qualifiedName = containingClass.getQualifiedName(); - if (!"java.util.Collections".equals(qualifiedName)) { + if (!CommonClassNames.JAVA_UTIL_COLLECTIONS.equals(qualifiedName)) { return; } registerError(expression, expression, replacement); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/ForCanBeForeachInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/ForCanBeForeachInspection.java index c8e8b0aa4d1a..acf5cf504593 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/ForCanBeForeachInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/ForCanBeForeachInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -204,7 +204,7 @@ public class ForCanBeForeachInspection extends BaseInspection{ out.append(' '); out.append(contentVariableName); out.append(": "); - final String listName; + @NonNls final String listName; if (listReference == null) { listName = "this"; } else { @@ -1067,7 +1067,7 @@ public class ForCanBeForeachInspection extends BaseInspection{ if(declaredClass == null){ return false; } - if(!ClassUtils.isSubclass(declaredClass, "java.util.Iterator")){ + if(!ClassUtils.isSubclass(declaredClass, CommonClassNames.JAVA_UTIL_ITERATOR)){ return false; } final PsiExpression initialValue = variable.getInitializer(); @@ -1102,8 +1102,10 @@ public class ForCanBeForeachInspection extends BaseInspection{ if(qualifierClass == null){ return false; } - if(!ClassUtils.isSubclass(qualifierClass, "java.lang.Iterable") && - !ClassUtils.isSubclass(qualifierClass, "java.util.Collection")){ + if(!ClassUtils.isSubclass(qualifierClass, + CommonClassNames.JAVA_LANG_ITERABLE) && + !ClassUtils.isSubclass(qualifierClass, + CommonClassNames.JAVA_UTIL_COLLECTION)){ return false; } final String iteratorName = variable.getName(); @@ -1291,7 +1293,7 @@ public class ForCanBeForeachInspection extends BaseInspection{ return false; } final PsiClass aClass = method.getContainingClass(); - return ClassUtils.isSubclass(aClass, "java.util.List"); + return ClassUtils.isSubclass(aClass, CommonClassNames.JAVA_UTIL_LIST); } private static boolean expressionIsArrayLengthLookup( diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/IndexOfReplaceableByContainsInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/IndexOfReplaceableByContainsInspection.java index 9ee0607e5eee..f8c46f80a7a3 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/IndexOfReplaceableByContainsInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/IndexOfReplaceableByContainsInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2009 Bas Leijdekkers + * Copyright 2005-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -227,7 +227,8 @@ public class IndexOfReplaceableByContainsInspection } final PsiType argumentType = arguments[0].getType(); if (argumentType == null || - !argumentType.equalsToText("java.lang.String")) { + !argumentType.equalsToText( + CommonClassNames.JAVA_LANG_STRING)) { return false; } final PsiExpression qualifier = @@ -237,7 +238,7 @@ public class IndexOfReplaceableByContainsInspection } final PsiType qualifierType = qualifier.getType(); return qualifierType != null && - qualifierType.equalsToText("java.lang.String"); + qualifierType.equalsToText(CommonClassNames.JAVA_LANG_STRING); } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/UnnecessaryBoxingInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/UnnecessaryBoxingInspection.java index b2c3a7d06ea7..cd6e43a5f0f1 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/UnnecessaryBoxingInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/UnnecessaryBoxingInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,18 +36,17 @@ import java.util.Map; public class UnnecessaryBoxingInspection extends BaseInspection { @NonNls static final Map s_boxingArgs = - new HashMap(9); + new HashMap(8); static { - s_boxingArgs.put("java.lang.Integer", "int"); - s_boxingArgs.put("java.lang.Short", "short"); - s_boxingArgs.put("java.lang.Boolean", "boolean"); - s_boxingArgs.put("java.lang.Long", "long"); - s_boxingArgs.put("java.lang.Byte", "byte"); - s_boxingArgs.put("java.lang.Float", "float"); - s_boxingArgs.put("java.lang.Double", "double"); - s_boxingArgs.put("java.lang.Long", "long"); - s_boxingArgs.put("java.lang.Character", "char"); + s_boxingArgs.put(CommonClassNames.JAVA_LANG_INTEGER, "int"); + s_boxingArgs.put(CommonClassNames.JAVA_LANG_SHORT, "short"); + s_boxingArgs.put(CommonClassNames.JAVA_LANG_BOOLEAN, "boolean"); + s_boxingArgs.put(CommonClassNames.JAVA_LANG_LONG, "long"); + s_boxingArgs.put(CommonClassNames.JAVA_LANG_BYTE, "byte"); + s_boxingArgs.put(CommonClassNames.JAVA_LANG_FLOAT, "float"); + s_boxingArgs.put(CommonClassNames.JAVA_LANG_DOUBLE, "double"); + s_boxingArgs.put(CommonClassNames.JAVA_LANG_CHARACTER, "char"); } @Override diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/UnnecessaryUnboxingInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/UnnecessaryUnboxingInspection.java index 1740ba53842e..090092544f3e 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/UnnecessaryUnboxingInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/UnnecessaryUnboxingInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,18 +38,17 @@ import java.util.Map; public class UnnecessaryUnboxingInspection extends BaseInspection { @NonNls static final Map s_unboxingMethods = - new HashMap(9); + new HashMap(8); static { - s_unboxingMethods.put("java.lang.Integer", "intValue"); - s_unboxingMethods.put("java.lang.Short", "shortValue"); - s_unboxingMethods.put("java.lang.Boolean", "booleanValue"); - s_unboxingMethods.put("java.lang.Long", "longValue"); - s_unboxingMethods.put("java.lang.Byte", "byteValue"); - s_unboxingMethods.put("java.lang.Float", "floatValue"); - s_unboxingMethods.put("java.lang.Long", "longValue"); - s_unboxingMethods.put("java.lang.Double", "doubleValue"); - s_unboxingMethods.put("java.lang.Character", "charValue"); + s_unboxingMethods.put(CommonClassNames.JAVA_LANG_INTEGER, "intValue"); + s_unboxingMethods.put(CommonClassNames.JAVA_LANG_SHORT, "shortValue"); + s_unboxingMethods.put(CommonClassNames.JAVA_LANG_BOOLEAN, "booleanValue"); + s_unboxingMethods.put(CommonClassNames.JAVA_LANG_LONG, "longValue"); + s_unboxingMethods.put(CommonClassNames.JAVA_LANG_BYTE, "byteValue"); + s_unboxingMethods.put(CommonClassNames.JAVA_LANG_FLOAT, "floatValue"); + s_unboxingMethods.put(CommonClassNames.JAVA_LANG_DOUBLE, "doubleValue"); + s_unboxingMethods.put(CommonClassNames.JAVA_LANG_CHARACTER, "charValue"); } @Override @@ -114,7 +113,7 @@ public class UnnecessaryUnboxingInspection extends BaseInspection { return; } final String classname = containingClass.getQualifiedName(); - if ("java.lang.Boolean".equals(classname)) { + if (CommonClassNames.JAVA_LANG_BOOLEAN.equals(classname)) { @NonNls final String name = field.getName(); if ("TRUE".equals(name)) { replaceExpression(methodCall, "true"); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/WhileCanBeForeachInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/WhileCanBeForeachInspection.java index 5c8fb9ae3ee8..de4d5b3e6670 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/WhileCanBeForeachInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/jdk15/WhileCanBeForeachInspection.java @@ -430,7 +430,7 @@ public class WhileCanBeForeachInspection extends BaseInspection { final PsiVariable variable = (PsiVariable)declaredElement; final PsiType variableType = variable.getType(); final PsiType iteratorType = - TypeUtils.getType("java.util.Iterator", whileStatement); + TypeUtils.getType(CommonClassNames.JAVA_UTIL_ITERATOR, whileStatement); if (iteratorType == null) { return false; } @@ -467,9 +467,10 @@ public class WhileCanBeForeachInspection extends BaseInspection { if (qualifierClass == null) { return false; } - if (!ClassUtils.isSubclass(qualifierClass, "java.lang.Iterable") && + if (!ClassUtils.isSubclass(qualifierClass, + CommonClassNames.JAVA_LANG_ITERABLE) && !ClassUtils.isSubclass(qualifierClass, - "java.util.Collection")) { + CommonClassNames.JAVA_UTIL_COLLECTION)) { return false; } final PsiExpression condition = whileStatement.getCondition(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/AssertEqualsBetweenInconvertibleTypesInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/AssertEqualsBetweenInconvertibleTypesInspection.java index b696b70a4b32..808e63ceceb5 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/AssertEqualsBetweenInconvertibleTypesInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/AssertEqualsBetweenInconvertibleTypesInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2007-2009 Bas Leijdekkers + * Copyright 2007-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,7 +90,8 @@ public class AssertEqualsBetweenInconvertibleTypesInspection final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] arguments = argumentList.getExpressions(); final int argumentIndex; - if (firstParameterType.equalsToText("java.lang.String")) { + if (firstParameterType.equalsToText( + CommonClassNames.JAVA_LANG_STRING)) { if (arguments.length < 3) { return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/AssertEqualsMayBeAssertSameInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/AssertEqualsMayBeAssertSameInspection.java index a165eba532f2..c47da7d6d2b9 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/AssertEqualsMayBeAssertSameInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/AssertEqualsMayBeAssertSameInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2008 Bas Leijdekkers + * Copyright 2008-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class AssertEqualsMayBeAssertSameInspection extends BaseInspection { @@ -49,7 +50,8 @@ public class AssertEqualsMayBeAssertSameInspection extends BaseInspection { @NotNull public String getName() { - return "Replace with 'assertSame()'"; + return InspectionGadgetsBundle.message( + "assertequals.may.be.assertsame.quickfix"); } @Override @@ -62,7 +64,7 @@ public class AssertEqualsMayBeAssertSameInspection extends BaseInspection { } final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) grandParent; - final String text = methodCallExpression.getText(); + @NonNls final String text = methodCallExpression.getText(); final String newExpressionText = text.replace("assertEquals", "assertSame"); replaceExpression(methodCallExpression, newExpressionText); @@ -83,7 +85,7 @@ public class AssertEqualsMayBeAssertSameInspection extends BaseInspection { super.visitMethodCallExpression(expression); final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String name = methodExpression.getReferenceName(); + @NonNls final String name = methodExpression.getReferenceName(); if (!"assertEquals".equals(name)) { return; } @@ -97,6 +99,9 @@ public class AssertEqualsMayBeAssertSameInspection extends BaseInspection { return; } final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } final String qualifiedName = aClass.getQualifiedName(); if (!"org.junit.Assert".equals(qualifiedName) && !"junit.framework.Assert".equals(qualifiedName)) { @@ -132,7 +137,8 @@ public class AssertEqualsMayBeAssertSameInspection extends BaseInspection { final PsiManager manager = argument1.getManager(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance( manager.getProject()); - final PsiClass objectClass = psiFacade.findClass("java.lang.Object", + final PsiClass objectClass = psiFacade.findClass( + CommonClassNames.JAVA_LANG_OBJECT, argumentClass.getResolveScope()); if (objectClass == null) { return false; diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java index 1e35e06ccbaa..9e4a87d1a1c6 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java @@ -89,7 +89,8 @@ public class ExpectedExceptionNeverThrownInspection } final PsiClassType classType = (PsiClassType) type; final PsiClass aClass = classType.resolve(); - if (ClassUtils.isSubclass(aClass, "java.lang.RuntimeException")) { + if (ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION)) { return; } final Set exceptionsThrown = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/MultipleExceptionsDeclaredOnTestMethodInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/MultipleExceptionsDeclaredOnTestMethodInspection.java index aaad522baac6..79aedfcc0dc8 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/MultipleExceptionsDeclaredOnTestMethodInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/MultipleExceptionsDeclaredOnTestMethodInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2009 Bas Leijdekkers + * Copyright 2009-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,8 +30,6 @@ import com.siyeh.ig.psiutils.TestUtils; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; -import java.text.MessageFormat; - public class MultipleExceptionsDeclaredOnTestMethodInspection extends BaseInspection { @@ -55,7 +53,7 @@ public class MultipleExceptionsDeclaredOnTestMethodInspection return new MultipleExceptionsDeclaredOnTestMethodFix(); } - private class MultipleExceptionsDeclaredOnTestMethodFix + private static class MultipleExceptionsDeclaredOnTestMethodFix extends InspectionGadgetsFix { @NotNull @@ -82,7 +80,7 @@ public class MultipleExceptionsDeclaredOnTestMethodInspection final GlobalSearchScope scope = referenceList.getResolveScope(); final PsiJavaCodeReferenceElement referenceElement = factory.createReferenceElementByFQClassName( - "java.lang.Exception", scope); + CommonClassNames.JAVA_LANG_EXCEPTION, scope); referenceList.add(referenceElement); } } @@ -92,7 +90,7 @@ public class MultipleExceptionsDeclaredOnTestMethodInspection return new RedundantExceptionDeclarationVisitor(); } - private class RedundantExceptionDeclarationVisitor + private static class RedundantExceptionDeclarationVisitor extends BaseInspectionVisitor { @Override diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/UnconstructableTestCaseInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/UnconstructableTestCaseInspection.java index e038467d4816..f7cd60625381 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/UnconstructableTestCaseInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/UnconstructableTestCaseInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,23 +25,27 @@ import org.jetbrains.annotations.NotNull; public class UnconstructableTestCaseInspection extends BaseInspection { + @Override @NotNull public String getID() { return "UnconstructableJUnitTestCase"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "unconstructable.test.case.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "unconstructable.test.case.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new UnconstructableTestCaseVisitor(); } @@ -79,7 +83,8 @@ public class UnconstructableTestCaseInspection extends BaseInspection { if (parametersCount == 1) { final PsiParameter[] parameters = parameterList.getParameters(); final PsiType type = parameters[0].getType(); - if (TypeUtils.typeEquals("java.lang.String", type)) { + if (TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, + type)) { hasStringConstructor = true; } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/memory/StringBufferFieldInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/memory/StringBufferFieldInspection.java index e9fe3ec859e8..28d92effda07 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/memory/StringBufferFieldInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/memory/StringBufferFieldInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.memory; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiField; import com.intellij.psi.PsiType; import com.siyeh.InspectionGadgetsBundle; @@ -24,12 +25,14 @@ import org.jetbrains.annotations.NotNull; public class StringBufferFieldInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "stringbuffer.field.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { final PsiType type = (PsiType)infos[0]; @@ -38,6 +41,7 @@ public class StringBufferFieldInspection extends BaseInspection { "stringbuffer.field.problem.descriptor", typeName); } + @Override public BaseInspectionVisitor buildVisitor() { return new StringBufferFieldVisitor(); } @@ -48,7 +52,7 @@ public class StringBufferFieldInspection extends BaseInspection { @Override public void visitField(@NotNull PsiField field) { super.visitField(field); final PsiType type = field.getType(); - if (!type.equalsToText("java.lang.StringBuffer") && + if (!type.equalsToText(CommonClassNames.JAVA_LANG_STRING_BUFFER) && !type.equalsToText("java.lang.StringBuilder")) { return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/BooleanMethodNameMustStartWithQuestionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/BooleanMethodNameMustStartWithQuestionInspection.java index 014539fe1e9b..ed2f94d95a79 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/BooleanMethodNameMustStartWithQuestionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/BooleanMethodNameMustStartWithQuestionInspection.java @@ -20,6 +20,7 @@ import com.intellij.codeInspection.ui.ListWrappingTableModel; import com.intellij.openapi.actionSystem.ActionToolbar; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiType; @@ -165,7 +166,8 @@ public class BooleanMethodNameMustStartWithQuestionInspection return; } else if(!returnType.equals(PsiType.BOOLEAN)){ if (ignoreBooleanMethods || - !returnType.equalsToText("java.lang.Boolean")) { + !returnType.equalsToText( + CommonClassNames.JAVA_LANG_BOOLEAN)) { return; } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/ConfusingMainMethodInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/ConfusingMainMethodInspection.java index d3075c06e9cb..7d6a25dc4ded 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/ConfusingMainMethodInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/ConfusingMainMethodInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,26 +27,31 @@ import org.jetbrains.annotations.NotNull; public class ConfusingMainMethodInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "confusing.main.method.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "confusing.main.method.problem.descriptor"); } + @Override protected InspectionGadgetsFix buildFix(Object... infos) { return new RenameFix(); } + @Override protected boolean buildQuickFixesOnlyForOnTheFlyErrors() { return true; } + @Override public BaseInspectionVisitor buildVisitor() { return new ConfusingMainMethodVisitor(); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/ExceptionNameDoesntEndWithExceptionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/ExceptionNameDoesntEndWithExceptionInspection.java index 03407504c78a..161ed2333a67 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/ExceptionNameDoesntEndWithExceptionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/ExceptionNameDoesntEndWithExceptionInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.naming; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiTypeParameter; import com.siyeh.InspectionGadgetsBundle; @@ -80,7 +81,8 @@ public class ExceptionNameDoesntEndWithExceptionInspection if (className.endsWith(exception)) { return; } - if (!ClassUtils.isSubclass(aClass, "java.lang.Exception")) { + if (!ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_LANG_EXCEPTION)) { return; } registerClassError(aClass); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/NonBooleanMethodNameMayNotStartWithQuestionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/NonBooleanMethodNameMayNotStartWithQuestionInspection.java index 62516b0a0913..1006bc859cfc 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/NonBooleanMethodNameMayNotStartWithQuestionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/NonBooleanMethodNameMayNotStartWithQuestionInspection.java @@ -20,6 +20,7 @@ import com.intellij.codeInspection.ui.ListWrappingTableModel; import com.intellij.openapi.actionSystem.ActionToolbar; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiType; import com.intellij.psi.search.searches.SuperMethodsSearch; @@ -154,7 +155,7 @@ public class NonBooleanMethodNameMayNotStartWithQuestionInspection return; } if(ignoreBooleanMethods && returnType.equalsToText( - "java.lang.Boolean")){ + CommonClassNames.JAVA_LANG_BOOLEAN)){ return; } final String name = method.getName(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/NonExceptionNameEndsWithExceptionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/NonExceptionNameEndsWithExceptionInspection.java index e41ec399214d..ed0e58e1db38 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/NonExceptionNameEndsWithExceptionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/NonExceptionNameEndsWithExceptionInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,7 +89,7 @@ public class NonExceptionNameEndsWithExceptionInspection final GlobalSearchScope scope = aClass.getResolveScope(); final PsiJavaCodeReferenceElement reference = factory.createReferenceElementByFQClassName( - "java.lang.Exception", scope); + CommonClassNames.JAVA_LANG_EXCEPTION, scope); final PsiJavaCodeReferenceElement[] referenceElements = extendsList.getReferenceElements(); for (PsiJavaCodeReferenceElement referenceElement : @@ -123,7 +123,8 @@ public class NonExceptionNameEndsWithExceptionInspection if (!className.endsWith(exception)) { return; } - if (ClassUtils.isSubclass(aClass, "java.lang.Exception")) { + if (ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_LANG_EXCEPTION)) { return; } registerClassError(aClass, className, Boolean.valueOf(isOnTheFly())); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/StandardVariableNamesInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/StandardVariableNamesInspection.java index a396b5f56a63..87345df6830b 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/StandardVariableNamesInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/StandardVariableNamesInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.naming; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiPrimitiveType; import com.intellij.psi.PsiType; import com.intellij.psi.PsiVariable; @@ -49,17 +50,17 @@ public class StandardVariableNamesInspection extends BaseInspection { s_expectedTypes.put("m", "int"); s_expectedTypes.put("n", "int"); s_expectedTypes.put("l", "long"); - s_expectedTypes.put("s", "java.lang.String"); - s_expectedTypes.put("str", "java.lang.String"); + s_expectedTypes.put("s", CommonClassNames.JAVA_LANG_STRING); + s_expectedTypes.put("str", CommonClassNames.JAVA_LANG_STRING); - s_boxingClasses.put("int", "java.lang.Integer"); - s_boxingClasses.put("short", "java.lang.Short"); - s_boxingClasses.put("boolean", "java.lang.Boolean"); - s_boxingClasses.put("long", "java.lang.Long"); - s_boxingClasses.put("byte", "java.lang.Byte"); - s_boxingClasses.put("float", "java.lang.Float"); - s_boxingClasses.put("double", "java.lang.Double"); - s_boxingClasses.put("char", "java.lang.Character"); + s_boxingClasses.put("int", CommonClassNames.JAVA_LANG_INTEGER); + s_boxingClasses.put("short", CommonClassNames.JAVA_LANG_SHORT); + s_boxingClasses.put("boolean", CommonClassNames.JAVA_LANG_BOOLEAN); + s_boxingClasses.put("long", CommonClassNames.JAVA_LANG_LONG); + s_boxingClasses.put("byte", CommonClassNames.JAVA_LANG_BYTE); + s_boxingClasses.put("float", CommonClassNames.JAVA_LANG_FLOAT); + s_boxingClasses.put("double", CommonClassNames.JAVA_LANG_DOUBLE); + s_boxingClasses.put("char", CommonClassNames.JAVA_LANG_CHARACTER); } @Override diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/CachedNumberConstructorCallInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/CachedNumberConstructorCallInspection.java index 17c9c5c847cc..f12ac56a8af7 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/CachedNumberConstructorCallInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/CachedNumberConstructorCallInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,28 +35,32 @@ public class CachedNumberConstructorCallInspection private static final Set cachedNumberTypes = new HashSet(); static { - cachedNumberTypes.add("java.lang.Long"); - cachedNumberTypes.add("java.lang.Byte"); - cachedNumberTypes.add("java.lang.Integer"); - cachedNumberTypes.add("java.lang.Short"); + cachedNumberTypes.add(CommonClassNames.JAVA_LANG_LONG); + cachedNumberTypes.add(CommonClassNames.JAVA_LANG_BYTE); + cachedNumberTypes.add(CommonClassNames.JAVA_LANG_INTEGER); + cachedNumberTypes.add(CommonClassNames.JAVA_LANG_SHORT); } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "cached.number.constructor.call.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "cached.number.constructor.call.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new LongConstructorVisitor(); } + @Override public InspectionGadgetsFix buildFix(Object... infos) { final PsiNewExpression expression = (PsiNewExpression) infos[0]; final PsiJavaCodeReferenceElement classReference = @@ -127,7 +131,8 @@ public class CachedNumberConstructorCallInspection final PsiExpression argument = arguments[0]; final PsiType argumentType = argument.getType(); if (argumentType == null || - argumentType.equalsToText("java.lang.String")) { + argumentType.equalsToText( + CommonClassNames.JAVA_LANG_STRING)) { return; } registerError(expression, expression); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/CharUsedInArithmeticContextInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/CharUsedInArithmeticContextInspection.java index 8e9018c198d4..30a2e959fcfc 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/CharUsedInArithmeticContextInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/CharUsedInArithmeticContextInspection.java @@ -69,7 +69,7 @@ public class CharUsedInArithmeticContextInspection extends BaseInspection { final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) parent; if (TypeUtils.expressionHasType(binaryExpression, - "java.lang.String")) { + CommonClassNames.JAVA_LANG_STRING)) { result.add(new CharUsedInArithmeticContentFix()); break; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/ImplicitNumericConversionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/ImplicitNumericConversionInspection.java index 554c8a3a1b73..347c1bef2645 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/ImplicitNumericConversionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/ImplicitNumericConversionInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -402,7 +402,7 @@ public class ImplicitNumericConversionInspection extends BaseInspection { return false; } final String className = aClass.getQualifiedName(); - return "java.lang.String".equals(className); + return CommonClassNames.JAVA_LANG_STRING.equals(className); } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/IntegerDivisionInFloatingPointContextInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/IntegerDivisionInFloatingPointContextInspection.java index ca992e218762..f02675881c22 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/IntegerDivisionInFloatingPointContextInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/IntegerDivisionInFloatingPointContextInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,25 +40,28 @@ public class IntegerDivisionInFloatingPointContextInspection s_integralTypes.add("short"); s_integralTypes.add("byte"); s_integralTypes.add("char"); - s_integralTypes.add("java.lang.Integer"); - s_integralTypes.add("java.lang.Long"); - s_integralTypes.add("java.lang.Short"); - s_integralTypes.add("java.lang.Byte"); - s_integralTypes.add("java.lang.Character"); + s_integralTypes.add(CommonClassNames.JAVA_LANG_INTEGER); + s_integralTypes.add(CommonClassNames.JAVA_LANG_LONG); + s_integralTypes.add(CommonClassNames.JAVA_LANG_SHORT); + s_integralTypes.add(CommonClassNames.JAVA_LANG_BYTE); + s_integralTypes.add(CommonClassNames.JAVA_LANG_CHARACTER); } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "integer.division.in.floating.point.context.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "integer.division.in.floating.point.context.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new IntegerDivisionInFloatingPointContextVisitor(); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/PointlessArithmeticExpressionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/PointlessArithmeticExpressionInspection.java index ea288a59537b..a15975403114 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/PointlessArithmeticExpressionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/numeric/PointlessArithmeticExpressionInspection.java @@ -174,7 +174,8 @@ public class PointlessArithmeticExpressionInspection if (!arithmeticTokens.contains(signText)) { return; } - if (TypeUtils.expressionHasType(expression, "java.lang.String")) { + if (TypeUtils.expressionHasType(expression, + CommonClassNames.JAVA_LANG_STRING)) { return; } final PsiExpression lhs = expression.getLOperand(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/BooleanConstructorInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/BooleanConstructorInspection.java index 2325887e05cd..3bc9130326cd 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/BooleanConstructorInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/BooleanConstructorInspection.java @@ -119,16 +119,20 @@ public class BooleanConstructorInspection extends BaseInspection { private static class BooleanConstructorVisitor extends BaseInspectionVisitor{ - @Override public void visitNewExpression(@NotNull PsiNewExpression expression){ + @Override public void visitNewExpression( + @NotNull PsiNewExpression expression){ super.visitNewExpression(expression); final PsiType type = expression.getType(); - if (type == null || !type.equalsToText("java.lang.Boolean")){ + if (type == null || !type.equalsToText( + CommonClassNames.JAVA_LANG_BOOLEAN)){ return; } final PsiClass aClass = ClassUtils.getContainingClass(expression); - if(aClass!=null && - "java.lang.Boolean".equals(aClass.getQualifiedName())){ - return; + if(aClass != null) { + final String qualifiedName = aClass.getQualifiedName(); + if(CommonClassNames.JAVA_LANG_BOOLEAN.equals(qualifiedName)){ + return; + } } registerError(expression); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/CollectionContainsUrlInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/CollectionContainsUrlInspection.java index 569651357bf4..7b65cecd59a9 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/CollectionContainsUrlInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/CollectionContainsUrlInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 Bas Leijdekkers + * Copyright 2007-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,12 +29,14 @@ import java.util.Set; public class CollectionContainsUrlInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "collection.contains.url.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { final ClassType type = (ClassType) infos[0]; @@ -42,6 +44,7 @@ public class CollectionContainsUrlInspection extends BaseInspection { "collection.contains.url.problem.decriptor", type); } + @Override public BaseInspectionVisitor buildVisitor() { return new CollectionContainsUrlVisitor(); } @@ -115,9 +118,9 @@ public class CollectionContainsUrlInspection extends BaseInspection { return ClassType.OTHER; } @NonNls final String className = aClass.getQualifiedName(); - if ("java.util.Set".equals(className)){ + if (CommonClassNames.JAVA_UTIL_SET.equals(className)){ return ClassType.SET; - } else if ("java.util.Map".equals(className)){ + } else if (CommonClassNames.JAVA_UTIL_MAP.equals(className)){ return ClassType.MAP; } final PsiClass[] supers = aClass.getSupers(); @@ -160,7 +163,8 @@ public class CollectionContainsUrlInspection extends BaseInspection { } final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) qualifierExpression; - final String methodName = methodExpression.getReferenceName(); + @NonNls final String methodName = + methodExpression.getReferenceName(); if (collectionType == ClassType.SET && !"add".equals(methodName)) { return; diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ConstantStringInternInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ConstantStringInternInspection.java index c4227c4f6fb4..3e436bec8a09 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ConstantStringInternInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ConstantStringInternInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2006-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,22 +29,26 @@ import org.jetbrains.annotations.NotNull; public class ConstantStringInternInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "constant.string.intern.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "constant.string.intern.problem.descriptor"); } + @Override public InspectionGadgetsFix buildFix(Object... infos) { return new ConstantStringInternFix(); } + @Override public BaseInspectionVisitor buildVisitor() { return new ConstantStringInternVisitor(); } @@ -57,6 +61,7 @@ public class ConstantStringInternInspection extends BaseInspection { "constant.string.intern.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); @@ -94,15 +99,12 @@ public class ConstantStringInternInspection extends BaseInspection { } final PsiExpression qualifier = methodExpression.getQualifierExpression(); - if(qualifier == null) - { + if(qualifier == null) { return; } - if(!PsiUtil.isConstantExpression(qualifier)) - { + if(!PsiUtil.isConstantExpression(qualifier)) { return; } - final PsiMethod method = expression.resolveMethod(); if (method == null) { return; @@ -112,7 +114,7 @@ public class ConstantStringInternInspection extends BaseInspection { return; } final String className = aClass.getQualifiedName(); - if (!"java.lang.String".equals(className)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { return; } registerMethodCallError(expression); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/DynamicRegexReplaceableByCompiledPatternInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/DynamicRegexReplaceableByCompiledPatternInspection.java index ae29e0a19e27..3bd5e9cc3b09 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/DynamicRegexReplaceableByCompiledPatternInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/DynamicRegexReplaceableByCompiledPatternInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2009 Bas Leijdekkers + * Copyright 2009-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -106,7 +106,7 @@ public class DynamicRegexReplaceableByCompiledPatternInspection final PsiExpressionList list = methodCallExpression.getArgumentList(); final PsiExpression[] expressions = list.getExpressions(); - final StringBuilder fieldText = + @NonNls final StringBuilder fieldText = new StringBuilder( "private static final java.util.regex.Pattern PATTERN = " + "java.util.regex.Pattern.compile("); @@ -121,11 +121,13 @@ public class DynamicRegexReplaceableByCompiledPatternInspection factory.createFieldFromText(fieldText.toString(), element); final PsiElement field = aClass.add(newField); - final StringBuilder expressionText = new StringBuilder("PATTERN."); - final String methodName = methodExpression.getReferenceName(); + @NonNls final StringBuilder expressionText = + new StringBuilder("PATTERN."); + @NonNls final String methodName = + methodExpression.getReferenceName(); final PsiExpression qualifier = methodExpression.getQualifierExpression(); - final String qualifierText; + @NonNls final String qualifierText; if (qualifier == null) { qualifierText = "this"; } else { @@ -167,8 +169,8 @@ public class DynamicRegexReplaceableByCompiledPatternInspection newMethodCallExpression); final PsiReferenceExpression reference = getReference(newMethodCallExpression); - HighlightUtils.showRenameTemplate(aClass, (PsiNameIdentifierOwner) field, - reference); + HighlightUtils.showRenameTemplate(aClass, + (PsiNameIdentifierOwner) field, reference); } private static PsiReferenceExpression getReference( @@ -232,7 +234,7 @@ public class DynamicRegexReplaceableByCompiledPatternInspection return false; } final String className = containingClass.getQualifiedName(); - return "java.lang.String".equals(className); + return CommonClassNames.JAVA_LANG_STRING.equals(className); } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/KeySetIterationMayUseEntrySetInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/KeySetIterationMayUseEntrySetInspection.java index 71d691517891..c7beffecbbad 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/KeySetIterationMayUseEntrySetInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/KeySetIterationMayUseEntrySetInspection.java @@ -379,7 +379,7 @@ public class KeySetIterationMayUseEntrySetInspection extends BaseInspection { return false; } final String className = aClass.getQualifiedName(); - if (!"java.util.Map".equals(className)) { + if (!CommonClassNames.JAVA_UTIL_MAP.equals(className)) { return false; } final GetValueFromMapChecker checker = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/LengthOneStringInIndexOfInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/LengthOneStringInIndexOfInspection.java index cbf91a9c9563..dd993c5332f7 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/LengthOneStringInIndexOfInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/LengthOneStringInIndexOfInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 Bas Leijdekkers + * Copyright 2006-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,17 +32,20 @@ import org.jetbrains.annotations.NotNull; public class LengthOneStringInIndexOfInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "length.one.string.in.indexof.display.name"); } + @Override @NotNull public String getID() { return "SingleCharacterStringConcatenation"; } + @Override @NotNull public String buildErrorString(Object... infos) { final String string = (String)infos[0]; @@ -52,10 +55,12 @@ public class LengthOneStringInIndexOfInspection escapedString); } + @Override public BaseInspectionVisitor buildVisitor() { return new LengthOneStringsInIndexOfVisitor(); } + @Override public InspectionGadgetsFix buildFix(Object... infos) { return new ReplaceStringsWithCharsFix(); } @@ -69,6 +74,7 @@ public class LengthOneStringInIndexOfInspection "length.one.strings.in.concatenation.replace.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiExpression expression = @@ -136,7 +142,7 @@ public class LengthOneStringInIndexOfInspection return false; } final String className = methodClass.getQualifiedName(); - return "java.lang.String".equals(className); + return CommonClassNames.JAVA_LANG_STRING.equals(className); } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/LengthOneStringsInConcatenationInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/LengthOneStringsInConcatenationInspection.java index fdfa83de8354..2bf7cfea75ad 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/LengthOneStringsInConcatenationInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/LengthOneStringsInConcatenationInspection.java @@ -160,7 +160,7 @@ public class LengthOneStringsInConcatenationInspection return false; } final String className = methodClass.getQualifiedName(); - return "java.lang.StringBuffer".equals(className) || + return CommonClassNames.JAVA_LANG_STRING_BUFFER.equals(className) || "java.lang.StringBuilder".equals(className); } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ManualArrayToCollectionCopyInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ManualArrayToCollectionCopyInspection.java index 440d6bdeeafe..a05b1233ee26 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ManualArrayToCollectionCopyInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ManualArrayToCollectionCopyInspection.java @@ -564,7 +564,7 @@ public class ManualArrayToCollectionCopyInspection extends BaseInspection { } final PsiClass containingClass = method.getContainingClass(); return ClassUtils.isSubclass(containingClass, - "java.util.Collection"); + CommonClassNames.JAVA_UTIL_COLLECTION); } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/MapReplaceableByEnumMapInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/MapReplaceableByEnumMapInspection.java index 0a6503a6aea8..d34df7f91724 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/MapReplaceableByEnumMapInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/MapReplaceableByEnumMapInspection.java @@ -67,7 +67,7 @@ public class MapReplaceableByEnumMapInspection extends BaseInspection { return; } if (!TypeUtils.expressionHasTypeOrSubtype(expression, - "java.util.Map")) { + CommonClassNames.JAVA_UTIL_MAP)) { return; } if (null != TypeUtils.expressionHasTypeOrSubtype(expression, diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/RedundantStringFormatCallInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/RedundantStringFormatCallInspection.java index 4f2a26848a17..b181bccf8848 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/RedundantStringFormatCallInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/RedundantStringFormatCallInspection.java @@ -119,7 +119,7 @@ public class RedundantStringFormatCallInspection extends BaseInspection { } final PsiClass aClass = (PsiClass) target; final String className = aClass.getQualifiedName(); - if (!"java.lang.String".equals(className)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { return; } final PsiExpression firstArgument = arguments[0]; @@ -130,7 +130,7 @@ public class RedundantStringFormatCallInspection extends BaseInspection { if (containsPercentN(firstArgument)) { return; } - if (firstType.equalsToText("java.lang.String") && + if (firstType.equalsToText(CommonClassNames.JAVA_LANG_STRING) && arguments.length == 1) { registerMethodCallError(expression); } else if (firstType.equalsToText("java.util.Locale")) { @@ -142,7 +142,8 @@ public class RedundantStringFormatCallInspection extends BaseInspection { if (secondType == null) { return; } - if (secondType.equalsToText("java.lang.String")) { + if (secondType.equalsToText( + CommonClassNames.JAVA_LANG_STRING)) { registerMethodCallError(expression); } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/SetReplaceableByEnumSetInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/SetReplaceableByEnumSetInspection.java index 1ad5ad6152d5..875369b46195 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/SetReplaceableByEnumSetInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/SetReplaceableByEnumSetInspection.java @@ -15,10 +15,7 @@ */ package com.siyeh.ig.performance; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiClassType; -import com.intellij.psi.PsiNewExpression; -import com.intellij.psi.PsiType; +import com.intellij.psi.*; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; @@ -69,7 +66,7 @@ public class SetReplaceableByEnumSetInspection extends BaseInspection { return; } if (!TypeUtils.expressionHasTypeOrSubtype(expression, - "java.util.Set")) { + CommonClassNames.JAVA_UTIL_SET)) { return; } if (TypeUtils.expressionHasTypeOrSubtype(expression, diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferMustHaveInitialCapacityInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferMustHaveInitialCapacityInspection.java index 0d0fcb4723f7..294704d8e494 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferMustHaveInitialCapacityInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferMustHaveInitialCapacityInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,7 @@ */ package com.siyeh.ig.performance; -import com.intellij.psi.PsiExpression; -import com.intellij.psi.PsiExpressionList; -import com.intellij.psi.PsiNewExpression; -import com.intellij.psi.PsiType; +import com.intellij.psi.*; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; @@ -28,23 +25,27 @@ import org.jetbrains.annotations.NotNull; public class StringBufferMustHaveInitialCapacityInspection extends BaseInspection { + @Override @NotNull public String getID() { return "StringBufferWithoutInitialCapacity"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "string.buffer.must.have.initial.capacity.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "string.buffer.must.have.initial.capacity.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new StringBufferInitialCapacityVisitor(); } @@ -52,11 +53,13 @@ public class StringBufferMustHaveInitialCapacityInspection private static class StringBufferInitialCapacityVisitor extends BaseInspectionVisitor { - @Override public void visitNewExpression(@NotNull PsiNewExpression expression) { + @Override public void visitNewExpression( + @NotNull PsiNewExpression expression) { super.visitNewExpression(expression); final PsiType type = expression.getType(); - if (!TypeUtils.typeEquals("java.lang.StringBuffer", type) && + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING_BUFFER, + type) && !TypeUtils.typeEquals("java.lang.StringBuilder", type)) { return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferReplaceableByStringBuilderInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferReplaceableByStringBuilderInspection.java index 2371c436e1ef..f5ffadd781c6 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferReplaceableByStringBuilderInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferReplaceableByStringBuilderInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,23 +37,27 @@ import java.util.Set; public class StringBufferReplaceableByStringBuilderInspection extends BaseInspection { + @Override @NotNull public String getID() { return "StringBufferMayBeStringBuilder"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "string.buffer.replaceable.by.string.builder.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "string.buffer.replaceable.by.string.builder.problem.descriptor"); } + @Override public InspectionGadgetsFix buildFix(Object... infos) { return new StringBufferMayBeStringBuilderFix(); } @@ -67,6 +71,7 @@ public class StringBufferReplaceableByStringBuilderInspection "string.buffer.replaceable.by.string.builder.replace.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement variableIdentifier = @@ -83,6 +88,7 @@ public class StringBufferReplaceableByStringBuilderInspection } } + @Override public BaseInspectionVisitor buildVisitor() { return new StringBufferReplaceableByStringBuilderVisitor(); } @@ -91,7 +97,8 @@ public class StringBufferReplaceableByStringBuilderInspection extends BaseInspectionVisitor { private static final Set excludes = new HashSet(Arrays.asList( - "java.lang.StringBuilder", "java.lang.StringBuffer")); + "java.lang.StringBuilder", + CommonClassNames.JAVA_LANG_STRING_BUFFER)); @Override public void visitLocalVariable( @NotNull PsiLocalVariable variable) { @@ -105,7 +112,8 @@ public class StringBufferReplaceableByStringBuilderInspection return; } final PsiType type = variable.getType(); - if (!TypeUtils.typeEquals("java.lang.StringBuffer", type)) { + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING_BUFFER, + type)) { return; } final PsiExpression initializer = variable.getInitializer(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferReplaceableByStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferReplaceableByStringInspection.java index 37e43109b3ed..6fdd92d6ea6f 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferReplaceableByStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferReplaceableByStringInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,8 @@ public class StringBufferReplaceableByStringInspection return; } final PsiType type = variable.getType(); - if(!TypeUtils.typeEquals("java.lang.StringBuffer", type) && + if(!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING_BUFFER, + type) && !TypeUtils.typeEquals("java.lang.StringBuilder", type)){ return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferToStringInConcatenationInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferToStringInConcatenationInspection.java index a975360dac89..6bb758357b70 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferToStringInConcatenationInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringBufferToStringInConcatenationInspection.java @@ -104,10 +104,12 @@ public class StringBufferToStringInConcatenationInspection } if (rhs.equals(expression)) { final PsiExpression lhs = parentBinary.getLOperand(); - if (!TypeUtils.expressionHasType(lhs, "java.lang.String")) { + if (!TypeUtils.expressionHasType(lhs, + CommonClassNames.JAVA_LANG_STRING)) { return; } - } else if (!TypeUtils.expressionHasType(rhs, "java.lang.String")) { + } else if (!TypeUtils.expressionHasType(rhs, + CommonClassNames.JAVA_LANG_STRING)) { return; } if (!isStringBufferToString(expression)) { @@ -137,7 +139,7 @@ public class StringBufferToStringInConcatenationInspection return false; } final String className = aClass.getQualifiedName(); - return "java.lang.StringBuffer".equals(className) || + return CommonClassNames.JAVA_LANG_STRING_BUFFER.equals(className) || "java.lang.StringBuilder".equals(className); } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringConcatenationInsideStringBufferAppendInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringConcatenationInsideStringBufferAppendInspection.java index 37f75fe7a8c9..4902392db056 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringConcatenationInsideStringBufferAppendInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringConcatenationInsideStringBufferAppendInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,16 +34,19 @@ import java.util.List; public class StringConcatenationInsideStringBufferAppendInspection extends BaseInspection { + @Override @NotNull public String getDisplayName(){ return InspectionGadgetsBundle.message( "string.concatenation.inside.string.buffer.append.display.name"); } + @Override public boolean isEnabledByDefault(){ return true; } + @Override @NotNull public String buildErrorString(Object... infos){ final PsiClass aClass = (PsiClass)infos[0]; @@ -53,10 +56,12 @@ public class StringConcatenationInsideStringBufferAppendInspection className); } + @Override public BaseInspectionVisitor buildVisitor(){ return new StringConcatenationInsideStringBufferAppendVisitor(); } + @Override public InspectionGadgetsFix buildFix(Object... infos){ return new ReplaceWithChainedAppendFix(); } @@ -70,6 +75,7 @@ public class StringConcatenationInsideStringBufferAppendInspection "string.concatenation.inside.string.buffer.append.replace.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException{ final PsiElement methodNameElement = descriptor.getPsiElement(); @@ -93,13 +99,17 @@ public class StringConcatenationInsideStringBufferAppendInspection useStringValueOf = false; } else{ final PsiClass containingClass = method.getContainingClass(); - final String qualifiedName = containingClass.getQualifiedName(); - if (qualifiedName == null){ + if (containingClass == null) { useStringValueOf = false; - } else{ - useStringValueOf = - !qualifiedName.equals("java.lang.StringBuffer") && - !qualifiedName.equals("java.lang.StringBuilder"); + } else { + final String qualifiedName = containingClass.getQualifiedName(); + if (qualifiedName == null){ + useStringValueOf = false; + } else{ + useStringValueOf = !qualifiedName.equals( + CommonClassNames.JAVA_LANG_STRING_BUFFER) && + !qualifiedName.equals("java.lang.StringBuilder"); + } } } final List expressions = @@ -134,7 +144,8 @@ public class StringConcatenationInsideStringBufferAppendInspection throws IncorrectOperationException{ final PsiType type = concatenation.getType(); if(concatenation instanceof PsiBinaryExpression){ - if (type != null && type.equalsToText("java.lang.String")){ + if (type != null && type.equalsToText( + CommonClassNames.JAVA_LANG_STRING)){ PsiBinaryExpression binaryExpression = (PsiBinaryExpression) concatenation; PsiExpression lhs = binaryExpression.getLOperand(); @@ -150,7 +161,8 @@ public class StringConcatenationInsideStringBufferAppendInspection while (lhs instanceof PsiBinaryExpression) { final PsiType lhsType = lhs.getType(); if (lhsType == null || - !lhsType.equalsToText("java.lang.String")) { + !lhsType.equalsToText( + CommonClassNames.JAVA_LANG_STRING)) { break; } binaryExpression = (PsiBinaryExpression)lhs; @@ -186,7 +198,7 @@ public class StringConcatenationInsideStringBufferAppendInspection return; } if (useStringValueOf && type != null && - !type.equalsToText("java.lang.String")){ + !type.equalsToText(CommonClassNames.JAVA_LANG_STRING)){ out.add("String.valueOf(" + concatenation.getText() + ')'); } else{ out.add(concatenation.getText()); @@ -225,15 +237,16 @@ public class StringConcatenationInsideStringBufferAppendInspection return; } final String className = containingClass.getQualifiedName(); - if("java.lang.StringBuffer".equals(className) || + if(CommonClassNames.JAVA_LANG_STRING_BUFFER.equals(className) || "java.lang.StringBuilder".equals(className)){ registerMethodCallError(expression, containingClass); return; } - final PsiManager manager = containingClass.getManager(); final Project project = containingClass.getProject(); - final PsiClass appendableClass = - JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.Appendable", GlobalSearchScope.allScope(project)); + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); + final PsiClass appendableClass = + psiFacade.findClass("java.lang.Appendable", + GlobalSearchScope.allScope(project)); if(appendableClass == null){ return; } @@ -254,7 +267,7 @@ public class StringConcatenationInsideStringBufferAppendInspection if(type == null){ return false; } - return type.equalsToText("java.lang.String"); + return type.equalsToText(CommonClassNames.JAVA_LANG_STRING); } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringConstructorInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringConstructorInspection.java index 905b1aa22a66..f5f45f2a9620 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringConstructorInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringConstructorInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,23 +36,27 @@ public class StringConstructorInspection extends BaseInspection { /** @noinspection PublicField*/ public boolean ignoreSubstringArguments = false; + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "string.constructor.display.name"); } + @Override @NotNull public String getID() { return "RedundantStringConstructorCall"; } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "string.constructor.problem.descriptor"); } + @Override @Nullable public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message( @@ -60,14 +64,17 @@ public class StringConstructorInspection extends BaseInspection { "ignoreSubstringArguments"); } + @Override public boolean isEnabledByDefault() { return true; } + @Override public BaseInspectionVisitor buildVisitor() { return new StringConstructorVisitor(); } + @Override public InspectionGadgetsFix buildFix(Object... infos) { final Boolean noArguments = (Boolean) infos[0]; return new StringConstructorFix(noArguments.booleanValue()); @@ -92,6 +99,7 @@ public class StringConstructorInspection extends BaseInspection { return m_name; } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiNewExpression expression = @@ -112,7 +120,8 @@ public class StringConstructorInspection extends BaseInspection { private class StringConstructorVisitor extends BaseInspectionVisitor { - @Override public void visitNewExpression(@NotNull PsiNewExpression expression) { + @Override public void visitNewExpression( + @NotNull PsiNewExpression expression) { super.visitNewExpression(expression); final PsiType type = expression.getType(); if (!TypeUtils.isJavaLangString(type)) { @@ -132,27 +141,35 @@ public class StringConstructorInspection extends BaseInspection { if (!TypeUtils.isJavaLangString(parameterType)) { return; } - if (ignoreSubstringArguments) { - if (argument instanceof PsiMethodCallExpression) { - final PsiMethodCallExpression methodCallExpression = - (PsiMethodCallExpression)argument; - final PsiReferenceExpression methodExpression = - methodCallExpression.getMethodExpression(); - final PsiElement element = methodExpression.resolve(); - if (element instanceof PsiMethod) { - final PsiMethod method = (PsiMethod)element; - final PsiClass aClass = method.getContainingClass(); - final String className = aClass.getQualifiedName(); - @NonNls final String methodName = method.getName(); - if ("java.lang.String".equals(className) && - methodName.equals("substring")) { - return; - } - } - } + if (ignoreSubstringArguments && + hasSubstringArgument(argument)) { + return; } } registerError(expression, Boolean.valueOf(arguments.length == 0)); } + + private boolean hasSubstringArgument(PsiExpression argument) { + if (!(argument instanceof PsiMethodCallExpression)) { + return false; + } + final PsiMethodCallExpression methodCallExpression = + (PsiMethodCallExpression)argument; + final PsiReferenceExpression methodExpression = + methodCallExpression.getMethodExpression(); + final PsiElement element = methodExpression.resolve(); + if (!(element instanceof PsiMethod)) { + return false; + } + final PsiMethod method = (PsiMethod)element; + final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return true; + } + final String className = aClass.getQualifiedName(); + @NonNls final String methodName = method.getName(); + return CommonClassNames.JAVA_LANG_STRING.equals(className) && + methodName.equals("substring"); + } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringEqualsEmptyStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringEqualsEmptyStringInspection.java index bd781f3131ab..54a922119ff4 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringEqualsEmptyStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringEqualsEmptyStringInspection.java @@ -32,18 +32,21 @@ import org.jetbrains.annotations.NotNull; public class StringEqualsEmptyStringInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "string.equals.empty.string.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "string.equals.empty.string.problem.descriptor"); } + @Override public InspectionGadgetsFix buildFix(Object... infos) { return new StringEqualsEmptyStringFix(); } @@ -57,6 +60,7 @@ public class StringEqualsEmptyStringInspection extends BaseInspection { "string.equals.empty.string.replace.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiIdentifier name = @@ -104,8 +108,8 @@ public class StringEqualsEmptyStringInspection extends BaseInspection { } final PsiType type = qualifierExpression.getType(); if (HardcodedMethodConstants.TO_STRING.equals(referenceName) && - type != null && - (type.equalsToText("java.lang.StringBuffer") || + type != null && (type.equalsToText( + CommonClassNames.JAVA_LANG_STRING_BUFFER) || type.equalsToText("java.lang.StringBuilder"))) { qualifierText = qualifierExpression.getText(); } else { @@ -118,6 +122,7 @@ public class StringEqualsEmptyStringInspection extends BaseInspection { } } + @Override public BaseInspectionVisitor buildVisitor() { return new StringEqualsEmptyStringVisitor(); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringReplaceableByStringBufferInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringReplaceableByStringBufferInspection.java index 8383b9524a68..f1d2b9072263 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringReplaceableByStringBufferInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringReplaceableByStringBufferInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,17 +31,20 @@ public class StringReplaceableByStringBufferInspection extends BaseInspection { @SuppressWarnings({"PublicField"}) public boolean onlyWarnOnLoop = true; + @Override @NotNull public String getID() { return "NonConstantStringShouldBeStringBuffer"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "string.replaceable.by.string.buffer.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( @@ -55,6 +58,7 @@ public class StringReplaceableByStringBufferInspection extends BaseInspection { this, "onlyWarnOnLoop"); } + @Override public BaseInspectionVisitor buildVisitor() { return new StringReplaceableByStringBufferVisitor(); } @@ -71,7 +75,8 @@ public class StringReplaceableByStringBufferInspection extends BaseInspection { return; } final PsiType type = variable.getType(); - if (!TypeUtils.typeEquals("java.lang.String", type)) { + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, + type)) { return; } if (!variableIsAppendedTo(variable, codeBlock)) { diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringToStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringToStringInspection.java index 7f40b235683b..95207235a263 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringToStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/StringToStringInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,30 +28,36 @@ import org.jetbrains.annotations.NotNull; public class StringToStringInspection extends BaseInspection { + @Override @NotNull public String getID() { return "RedundantStringToString"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message("string.to.string.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "string.to.string.problem.descriptor"); } + @Override public boolean isEnabledByDefault() { return true; } + @Override public BaseInspectionVisitor buildVisitor() { return new StringToStringVisitor(); } + @Override public InspectionGadgetsFix buildFix(Object... infos) { return new StringToStringFix(); } @@ -64,6 +70,7 @@ public class StringToStringInspection extends BaseInspection { "constant.conditional.expression.simplify.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiMethodCallExpression call = @@ -104,7 +111,7 @@ public class StringToStringInspection extends BaseInspection { return; } final String className = aClass.getQualifiedName(); - if (!"java.lang.String".equals(className)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { return; } registerError(expression); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/SubstringZeroInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/SubstringZeroInspection.java index 8eaad273de98..84d67c9edef7 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/SubstringZeroInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/SubstringZeroInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,22 +29,26 @@ import org.jetbrains.annotations.NotNull; public class SubstringZeroInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "substring.zero.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "substring.zero.problem.descriptor"); } + @Override public InspectionGadgetsFix buildFix(Object... infos) { return new SubstringZeroFix(); } + @Override public BaseInspectionVisitor buildVisitor() { return new SubstringZeroVisitor(); } @@ -57,6 +61,7 @@ public class SubstringZeroInspection extends BaseInspection { "constant.conditional.expression.simplify.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiMethodCallExpression call = @@ -73,6 +78,7 @@ public class SubstringZeroInspection extends BaseInspection { } private static class SubstringZeroVisitor extends BaseInspectionVisitor { + @Override public void visitMethodCallExpression( @NotNull PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); @@ -83,16 +89,16 @@ public class SubstringZeroInspection extends BaseInspection { if (!"substring".equals(methodName)) { return; } - final PsiExpressionList argList = expression.getArgumentList(); - final PsiExpression[] args = argList.getExpressions(); - if (args.length != 1) { + final PsiExpressionList argumentList = expression.getArgumentList(); + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 1) { return; } - final PsiExpression arg = args[0]; - if (arg == null) { + final PsiExpression argument = arguments[0]; + if (argument == null) { return; } - if (!ExpressionUtils.isZero(arg)) { + if (!ExpressionUtils.isZero(argument)) { return; } final PsiMethod method = expression.resolveMethod(); @@ -104,7 +110,7 @@ public class SubstringZeroInspection extends BaseInspection { return; } final String className = aClass.getQualifiedName(); - if (!"java.lang.String".equals(className)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(className)) { return; } registerError(expression); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ToArrayCallWithZeroLengthArrayArgumentInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ToArrayCallWithZeroLengthArrayArgumentInspection.java index 98e464c4728c..bbcfa234ee1c 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ToArrayCallWithZeroLengthArrayArgumentInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/ToArrayCallWithZeroLengthArrayArgumentInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2007-2008 Bas Leijdekkers + * Copyright 2007-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import com.siyeh.ig.psiutils.ClassUtils; import com.siyeh.ig.psiutils.CollectionUtils; import com.siyeh.ig.psiutils.ExpressionUtils; import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -121,7 +122,7 @@ public class ToArrayCallWithZeroLengthArrayArgumentInspection return null; } final PsiExpression dimension = dimensions[0]; - final String replacementText = qualifierText + ".size()"; + @NonNls final String replacementText = qualifierText + ".size()"; return getElementText(expression, dimension, replacementText); } else if (argument instanceof PsiReferenceExpression) { final PsiReferenceExpression referenceExpression = @@ -133,7 +134,7 @@ public class ToArrayCallWithZeroLengthArrayArgumentInspection } final PsiType componentType = type.getComponentType(); final String typeText = componentType.getCanonicalText(); - final String replacementText = + @NonNls final String replacementText = "new " + typeText + "[" + qualifierText + ".size()]"; return getElementText(expression, referenceExpression, replacementText); @@ -155,7 +156,8 @@ public class ToArrayCallWithZeroLengthArrayArgumentInspection super.visitMethodCallExpression(expression); final PsiReferenceExpression methodExpression = expression.getMethodExpression(); - final String methodName = methodExpression.getReferenceName(); + @NonNls final String methodName = + methodExpression.getReferenceName(); if (!"toArray".equals(methodName)) { return; } @@ -190,7 +192,7 @@ public class ToArrayCallWithZeroLengthArrayArgumentInspection } final PsiClass containingClass = method.getContainingClass(); if (!ClassUtils.isSubclass(containingClass, - "java.util.Collection")) { + CommonClassNames.JAVA_UTIL_COLLECTION)) { return; } registerMethodCallError(expression, expression, argument); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/TrivialStringConcatenationInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/TrivialStringConcatenationInspection.java index 2dfbd2375d52..fcae9d3eb83d 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/TrivialStringConcatenationInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/TrivialStringConcatenationInspection.java @@ -17,6 +17,7 @@ package com.siyeh.ig.performance; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiBinaryExpression; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiExpression; @@ -75,7 +76,8 @@ public class TrivialStringConcatenationInspection extends BaseInspection { } else { replacementText = replacement.getText(); } - if (TypeUtils.expressionHasType(replacement, "java.lang.String")) { + if (TypeUtils.expressionHasType(replacement, + CommonClassNames.JAVA_LANG_STRING)) { return replacementText; } } @@ -127,7 +129,8 @@ public class TrivialStringConcatenationInspection extends BaseInspection { if (!(expression.getROperand() != null)) { return; } - if (!TypeUtils.expressionHasType(expression, "java.lang.String")) { + if (!TypeUtils.expressionHasType(expression, + CommonClassNames.JAVA_LANG_STRING)) { return; } final PsiExpression lhs = expression.getLOperand(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/UnnecessaryTemporaryOnConversionFromStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/UnnecessaryTemporaryOnConversionFromStringInspection.java index 7d9fe7320a39..640ab30e61bc 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/UnnecessaryTemporaryOnConversionFromStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/UnnecessaryTemporaryOnConversionFromStringInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,25 +40,28 @@ public class UnnecessaryTemporaryOnConversionFromStringInspection new HashMap(7); static { - s_conversionMap.put("java.lang.Boolean", "valueOf"); - s_conversionMap.put("java.lang.Byte", "parseByte"); - s_conversionMap.put("java.lang.Double", "parseDouble"); - s_conversionMap.put("java.lang.Float", "parseFloat"); - s_conversionMap.put("java.lang.Integer", "parseInt"); - s_conversionMap.put("java.lang.Long", "parseLong"); - s_conversionMap.put("java.lang.Short", "parseShort"); + s_conversionMap.put(CommonClassNames.JAVA_LANG_BOOLEAN, "valueOf"); + s_conversionMap.put(CommonClassNames.JAVA_LANG_BYTE, "parseByte"); + s_conversionMap.put(CommonClassNames.JAVA_LANG_DOUBLE, "parseDouble"); + s_conversionMap.put(CommonClassNames.JAVA_LANG_FLOAT, "parseFloat"); + s_conversionMap.put(CommonClassNames.JAVA_LANG_INTEGER, "parseInt"); + s_conversionMap.put(CommonClassNames.JAVA_LANG_LONG, "parseLong"); + s_conversionMap.put(CommonClassNames.JAVA_LANG_SHORT, "parseShort"); } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "unnecessary.temporary.on.conversion.from.string.display.name"); } + @Override public boolean isEnabledByDefault(){ return true; } + @Override @NotNull public String buildErrorString(Object... infos) { final String replacementString = @@ -94,7 +97,7 @@ public class UnnecessaryTemporaryOnConversionFromStringInspection final String qualifierType = type.getPresentableText(); final String canonicalType = type.getCanonicalText(); final String conversionName = s_conversionMap.get(canonicalType); - if (TypeUtils.typeEquals("java.lang.Boolean", type)) { + if (TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_BOOLEAN, type)) { if (!PsiUtil.isLanguageLevel5OrHigher(expression)) { return qualifierType + '.' + conversionName + '(' + arg.getText() + ").booleanValue()"; @@ -108,6 +111,7 @@ public class UnnecessaryTemporaryOnConversionFromStringInspection } } + @Override @Nullable public InspectionGadgetsFix buildFix(Object... infos) { final String replacementExpression = @@ -137,6 +141,7 @@ public class UnnecessaryTemporaryOnConversionFromStringInspection return m_name; } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiMethodCallExpression expression = @@ -150,6 +155,7 @@ public class UnnecessaryTemporaryOnConversionFromStringInspection } } + @Override public BaseInspectionVisitor buildVisitor() { return new UnnecessaryTemporaryObjectVisitor(); } @@ -162,13 +168,13 @@ public class UnnecessaryTemporaryOnConversionFromStringInspection new HashMap(7); static { - s_basicTypeMap.put("java.lang.Boolean", "booleanValue"); - s_basicTypeMap.put("java.lang.Byte", "byteValue"); - s_basicTypeMap.put("java.lang.Double", "doubleValue"); - s_basicTypeMap.put("java.lang.Float", "floatValue"); - s_basicTypeMap.put("java.lang.Integer", "intValue"); - s_basicTypeMap.put("java.lang.Long", "longValue"); - s_basicTypeMap.put("java.lang.Short", "shortValue"); + s_basicTypeMap.put(CommonClassNames.JAVA_LANG_BOOLEAN, "booleanValue"); + s_basicTypeMap.put(CommonClassNames.JAVA_LANG_BYTE, "byteValue"); + s_basicTypeMap.put(CommonClassNames.JAVA_LANG_DOUBLE, "doubleValue"); + s_basicTypeMap.put(CommonClassNames.JAVA_LANG_FLOAT, "floatValue"); + s_basicTypeMap.put(CommonClassNames.JAVA_LANG_INTEGER, "intValue"); + s_basicTypeMap.put(CommonClassNames.JAVA_LANG_LONG, "longValue"); + s_basicTypeMap.put(CommonClassNames.JAVA_LANG_SHORT, "shortValue"); } @Override public void visitMethodCallExpression( @@ -186,17 +192,18 @@ public class UnnecessaryTemporaryOnConversionFromStringInspection if (!(qualifier instanceof PsiNewExpression)) { return; } - final PsiNewExpression newExp = (PsiNewExpression) qualifier; - final PsiExpressionList argList = newExp.getArgumentList(); - if (argList== null) { + final PsiNewExpression newExpression = (PsiNewExpression) qualifier; + final PsiExpressionList argumentList = + newExpression.getArgumentList(); + if (argumentList == null) { return; } - final PsiExpression[] args = argList.getExpressions(); - if (args.length != 1) { + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 1) { return; } - final PsiType argType = args[0].getType(); - if (!TypeUtils.isJavaLangString(argType)) { + final PsiType argumentType = arguments[0].getType(); + if (!TypeUtils.isJavaLangString(argumentType)) { return; } final PsiType type = qualifier.getType(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/UnnecessaryTemporaryOnConversionToStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/UnnecessaryTemporaryOnConversionToStringInspection.java index 3c1e30e6d688..85d23d9e7bd5 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/performance/UnnecessaryTemporaryOnConversionToStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/performance/UnnecessaryTemporaryOnConversionToStringInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,16 +34,19 @@ import java.util.Set; public class UnnecessaryTemporaryOnConversionToStringInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "unnecessary.temporary.on.conversion.to.string.display.name"); } + @Override public boolean isEnabledByDefault() { return true; } + @Override @NotNull public String buildErrorString(Object... infos) { final String replacementString = calculateReplacementExpression( @@ -82,6 +85,7 @@ public class UnnecessaryTemporaryOnConversionToStringInspection return qualifierType + ".toString(" + argumentText + ')'; } + @Override public InspectionGadgetsFix buildFix(Object... infos) { final String replacement = calculateReplacementExpression( (PsiMethodCallExpression)infos[0]); @@ -106,6 +110,7 @@ public class UnnecessaryTemporaryOnConversionToStringInspection return m_name; } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiMethodCallExpression expression = @@ -119,6 +124,7 @@ public class UnnecessaryTemporaryOnConversionToStringInspection } } + @Override public BaseInspectionVisitor buildVisitor() { return new UnnecessaryTemporaryObjectVisitor(); } @@ -130,14 +136,14 @@ public class UnnecessaryTemporaryOnConversionToStringInspection private static final Set s_basicTypes = new HashSet(8); static { - s_basicTypes.add("java.lang.Boolean"); - s_basicTypes.add("java.lang.Byte"); - s_basicTypes.add("java.lang.Character"); - s_basicTypes.add("java.lang.Double"); - s_basicTypes.add("java.lang.Float"); - s_basicTypes.add("java.lang.Integer"); - s_basicTypes.add("java.lang.Long"); - s_basicTypes.add("java.lang.Short"); + s_basicTypes.add(CommonClassNames.JAVA_LANG_BOOLEAN); + s_basicTypes.add(CommonClassNames.JAVA_LANG_BYTE); + s_basicTypes.add(CommonClassNames.JAVA_LANG_CHARACTER); + s_basicTypes.add(CommonClassNames.JAVA_LANG_DOUBLE); + s_basicTypes.add(CommonClassNames.JAVA_LANG_FLOAT); + s_basicTypes.add(CommonClassNames.JAVA_LANG_INTEGER); + s_basicTypes.add(CommonClassNames.JAVA_LANG_LONG); + s_basicTypes.add(CommonClassNames.JAVA_LANG_SHORT); } @Override public void visitMethodCallExpression( @@ -168,7 +174,8 @@ public class UnnecessaryTemporaryOnConversionToStringInspection final PsiExpression argument = arguments[0]; final PsiType argumentType = argument.getType(); if (argumentType != null && - argumentType.equalsToText("java.lang.String")) { + argumentType.equalsToText( + CommonClassNames.JAVA_LANG_STRING)) { return; } final PsiType type = qualifier.getType(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ClassUtils.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ClassUtils.java index fd4806b44657..751b5b4c6cb2 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ClassUtils.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ClassUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,15 +57,15 @@ public class ClassUtils { primitiveNumericTypes.add(PsiType.FLOAT); primitiveNumericTypes.add(PsiType.DOUBLE); - immutableTypes.add("java.lang.Boolean"); - immutableTypes.add("java.lang.Character"); - immutableTypes.add("java.lang.Short"); - immutableTypes.add("java.lang.Integer"); - immutableTypes.add("java.lang.Long"); - immutableTypes.add("java.lang.Float"); - immutableTypes.add("java.lang.Double"); - immutableTypes.add("java.lang.Byte"); - immutableTypes.add("java.lang.String"); + immutableTypes.add(CommonClassNames.JAVA_LANG_BOOLEAN); + immutableTypes.add(CommonClassNames.JAVA_LANG_CHARACTER); + immutableTypes.add(CommonClassNames.JAVA_LANG_SHORT); + immutableTypes.add(CommonClassNames.JAVA_LANG_INTEGER); + immutableTypes.add(CommonClassNames.JAVA_LANG_LONG); + immutableTypes.add(CommonClassNames.JAVA_LANG_FLOAT); + immutableTypes.add(CommonClassNames.JAVA_LANG_DOUBLE); + immutableTypes.add(CommonClassNames.JAVA_LANG_BYTE); + immutableTypes.add(CommonClassNames.JAVA_LANG_STRING); immutableTypes.add("java.awt.Font"); immutableTypes.add("java.awt.Color"); immutableTypes.add("java.math.BigDecimal"); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/CloneUtils.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/CloneUtils.java index ab81945c625c..3d7a244d43d6 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/CloneUtils.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/CloneUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,17 +27,19 @@ public class CloneUtils{ } public static boolean isCloneable(@NotNull PsiClass aClass){ - return ClassUtils.isSubclass(aClass, "java.lang.Cloneable"); + return ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_LANG_CLONEABLE); } public static boolean isDirectlyCloneable(@NotNull PsiClass aClass){ final PsiClass[] interfaces = aClass.getInterfaces(); for(PsiClass anInterface : interfaces){ - if(anInterface != null){ - final String qualifiedName = anInterface.getQualifiedName(); - if("java.lang.Cloneable".equals(qualifiedName)){ - return true; - } + if (anInterface == null) { + continue; + } + final String qualifiedName = anInterface.getQualifiedName(); + if(CommonClassNames.JAVA_LANG_CLONEABLE.equals(qualifiedName)){ + return true; } } return false; diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/CollectionUtils.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/CollectionUtils.java index 484a20e89eee..40c0ee0a1713 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/CollectionUtils.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/CollectionUtils.java @@ -58,18 +58,12 @@ public class CollectionUtils{ s_collectionClassesRequiringCapacity.add("java.util.Hashtable"); s_collectionClassesRequiringCapacity.add("java.util.HashSet"); s_collectionClassesRequiringCapacity.add("java.util.LinkedHashSet"); - s_collectionClassesRequiringCapacity - .add("com.sun.java.util.collections.BitSet"); - s_collectionClassesRequiringCapacity - .add("com.sun.java.util.collections.Vector"); - s_collectionClassesRequiringCapacity - .add("com.sun.java.util.collections.ArrayList"); - s_collectionClassesRequiringCapacity - .add("com.sun.java.util.collections.HashMap"); - s_collectionClassesRequiringCapacity - .add("com.sun.java.util.collections.Hashtable"); - s_collectionClassesRequiringCapacity - .add("com.sun.java.util.collections.HashSet"); + s_collectionClassesRequiringCapacity.add("com.sun.java.util.collections.BitSet"); + s_collectionClassesRequiringCapacity.add("com.sun.java.util.collections.Vector"); + s_collectionClassesRequiringCapacity.add("com.sun.java.util.collections.ArrayList"); + s_collectionClassesRequiringCapacity.add("com.sun.java.util.collections.HashMap"); + s_collectionClassesRequiringCapacity.add("com.sun.java.util.collections.Hashtable"); + s_collectionClassesRequiringCapacity.add("com.sun.java.util.collections.HashSet"); s_allCollectionClasses.add("java.util.ArrayList"); s_allCollectionClasses.add("java.util.EnumMap"); @@ -102,8 +96,8 @@ public class CollectionUtils{ s_allCollectionClassesAndInterfaces.add("java.util.AbstractSequentialList"); s_allCollectionClassesAndInterfaces.add("java.util.AbstractSet"); s_allCollectionClassesAndInterfaces.add("java.util.ArrayList"); - s_allCollectionClassesAndInterfaces.add("java.util.Collection"); - s_allCollectionClassesAndInterfaces.add("java.util.Dictionary"); + s_allCollectionClassesAndInterfaces.add(CommonClassNames.JAVA_UTIL_COLLECTION); + s_allCollectionClassesAndInterfaces.add(CommonClassNames.JAVA_UTIL_DICTIONARY); s_allCollectionClassesAndInterfaces.add("java.util.HashMap"); s_allCollectionClassesAndInterfaces.add("java.util.HashSet"); s_allCollectionClassesAndInterfaces.add("java.util.Hashtable"); @@ -111,10 +105,10 @@ public class CollectionUtils{ s_allCollectionClassesAndInterfaces.add("java.util.LinkedHashMap"); s_allCollectionClassesAndInterfaces.add("java.util.LinkedHashSet"); s_allCollectionClassesAndInterfaces.add("java.util.LinkedList"); - s_allCollectionClassesAndInterfaces.add("java.util.List"); - s_allCollectionClassesAndInterfaces.add("java.util.Map"); + s_allCollectionClassesAndInterfaces.add(CommonClassNames.JAVA_UTIL_LIST); + s_allCollectionClassesAndInterfaces.add(CommonClassNames.JAVA_UTIL_MAP); s_allCollectionClassesAndInterfaces.add("java.util.Queue"); - s_allCollectionClassesAndInterfaces.add("java.util.Set"); + s_allCollectionClassesAndInterfaces.add(CommonClassNames.JAVA_UTIL_SET); s_allCollectionClassesAndInterfaces.add("java.util.SortedMap"); s_allCollectionClassesAndInterfaces.add("java.util.SortedSet"); s_allCollectionClassesAndInterfaces.add("java.util.Stack"); @@ -122,34 +116,20 @@ public class CollectionUtils{ s_allCollectionClassesAndInterfaces.add("java.util.TreeSet"); s_allCollectionClassesAndInterfaces.add("java.util.Vector"); s_allCollectionClassesAndInterfaces.add("java.util.WeakHashMap"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.ArrayList"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.Collection"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.HashMap"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.HashSet"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.Hashtable"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.LinkedList"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.List"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.Map"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.Set"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.SortedMap"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.SortedSet"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.TreeMap"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.TreeSet"); - s_allCollectionClassesAndInterfaces - .add("com.sun.java.util.collections.Vector"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.ArrayList"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.Collection"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.HashMap"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.HashSet"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.Hashtable"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.LinkedList"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.List"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.Map"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.Set"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.SortedMap"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.SortedSet"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.TreeMap"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.TreeSet"); + s_allCollectionClassesAndInterfaces.add("com.sun.java.util.collections.Vector"); s_interfaceForCollection.put("ArrayList", "List"); s_interfaceForCollection.put("EnumMap", "Map"); @@ -166,41 +146,29 @@ public class CollectionUtils{ s_interfaceForCollection.put("TreeSet", "SortedSet"); s_interfaceForCollection.put("Vector", "List"); s_interfaceForCollection.put("WeakHashMap", "Map"); - s_interfaceForCollection.put("java.util.ArrayList", "java.util.List"); - s_interfaceForCollection.put("java.util.EnumMap", "java.util.Map"); - s_interfaceForCollection.put("java.util.EnumSet", "java.util.Set"); - s_interfaceForCollection.put("java.util.HashMap", "java.util.Map"); - s_interfaceForCollection.put("java.util.HashSet", "java.util.Set"); - s_interfaceForCollection.put("java.util.Hashtable", "java.util.Map"); - s_interfaceForCollection - .put("java.util.IdentityHashMap", "java.util.Map"); - s_interfaceForCollection - .put("java.util.LinkedHashMap", "java.util.Map"); - s_interfaceForCollection - .put("java.util.LinkedHashSet", "java.util.Set"); - s_interfaceForCollection.put("java.util.LinkedList", "java.util.List"); - s_interfaceForCollection.put("java.util.PriorityQueue", - "java.util.Queue"); - s_interfaceForCollection.put("java.util.TreeMap", "java.util.Map"); - s_interfaceForCollection.put("java.util.TreeSet", "java.util.Set"); - s_interfaceForCollection.put("java.util.Vector", "java.util.List"); - s_interfaceForCollection.put("java.util.WeakHashMap", "java.util.Map"); - s_interfaceForCollection.put("com.sun.java.util.collections.HashSet", - "com.sun.java.util.collections.Set"); - s_interfaceForCollection.put("com.sun.java.util.collections.TreeSet", - "com.sun.java.util.collections.Set"); - s_interfaceForCollection.put("com.sun.java.util.collections.Vector", - "com.sun.java.util.collections.List"); - s_interfaceForCollection.put("com.sun.java.util.collections.ArrayList", - "com.sun.java.util.collections.List"); - s_interfaceForCollection.put("com.sun.java.util.collections.LinkedList", - "com.sun.java.util.collections.List"); - s_interfaceForCollection.put("com.sun.java.util.collections.TreeMap", - "com.sun.java.util.collections.Map"); - s_interfaceForCollection.put("com.sun.java.util.collections.HashMap", - "com.sun.java.util.collections.Map"); - s_interfaceForCollection.put("com.sun.java.util.collections.Hashtable", - "com.sun.java.util.collections.Map"); + s_interfaceForCollection.put("java.util.ArrayList", CommonClassNames.JAVA_UTIL_LIST); + s_interfaceForCollection.put("java.util.EnumMap", CommonClassNames.JAVA_UTIL_MAP); + s_interfaceForCollection.put("java.util.EnumSet", CommonClassNames.JAVA_UTIL_SET); + s_interfaceForCollection.put("java.util.HashMap", CommonClassNames.JAVA_UTIL_MAP); + s_interfaceForCollection.put("java.util.HashSet", CommonClassNames.JAVA_UTIL_SET); + s_interfaceForCollection.put("java.util.Hashtable", CommonClassNames.JAVA_UTIL_MAP); + s_interfaceForCollection.put("java.util.IdentityHashMap", CommonClassNames.JAVA_UTIL_MAP); + s_interfaceForCollection.put("java.util.LinkedHashMap", CommonClassNames.JAVA_UTIL_MAP); + s_interfaceForCollection.put("java.util.LinkedHashSet", CommonClassNames.JAVA_UTIL_SET); + s_interfaceForCollection.put("java.util.LinkedList", CommonClassNames.JAVA_UTIL_LIST); + s_interfaceForCollection.put("java.util.PriorityQueue", "java.util.Queue"); + s_interfaceForCollection.put("java.util.TreeMap", CommonClassNames.JAVA_UTIL_MAP); + s_interfaceForCollection.put("java.util.TreeSet", CommonClassNames.JAVA_UTIL_SET); + s_interfaceForCollection.put("java.util.Vector", CommonClassNames.JAVA_UTIL_LIST); + s_interfaceForCollection.put("java.util.WeakHashMap", CommonClassNames.JAVA_UTIL_MAP); + s_interfaceForCollection.put("com.sun.java.util.collections.HashSet", "com.sun.java.util.collections.Set"); + s_interfaceForCollection.put("com.sun.java.util.collections.TreeSet", "com.sun.java.util.collections.Set"); + s_interfaceForCollection.put("com.sun.java.util.collections.Vector", "com.sun.java.util.collections.List"); + s_interfaceForCollection.put("com.sun.java.util.collections.ArrayList", "com.sun.java.util.collections.List"); + s_interfaceForCollection.put("com.sun.java.util.collections.LinkedList", "com.sun.java.util.collections.List"); + s_interfaceForCollection.put("com.sun.java.util.collections.TreeMap", "com.sun.java.util.collections.Map"); + s_interfaceForCollection.put("com.sun.java.util.collections.HashMap", "com.sun.java.util.collections.Map"); + s_interfaceForCollection.put("com.sun.java.util.collections.Hashtable", "com.sun.java.util.collections.Map"); } private CollectionUtils(){ diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ExceptionUtils.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ExceptionUtils.java index 4c9f63cd1a67..e10283cad899 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ExceptionUtils.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ExceptionUtils.java @@ -31,10 +31,10 @@ public class ExceptionUtils{ new HashSet(4); static { - s_genericExceptionTypes.add("java.lang.Throwable"); - s_genericExceptionTypes.add("java.lang.Exception"); - s_genericExceptionTypes.add("java.lang.RuntimeException"); - s_genericExceptionTypes.add("java.lang.Error"); + s_genericExceptionTypes.add(CommonClassNames.JAVA_LANG_THROWABLE); + s_genericExceptionTypes.add(CommonClassNames.JAVA_LANG_EXCEPTION); + s_genericExceptionTypes.add(CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION); + s_genericExceptionTypes.add(CommonClassNames.JAVA_LANG_ERROR); } @NotNull public static Set calculateExceptionsThrown( diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ExpressionUtils.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ExpressionUtils.java index 5a0f1fdbef8a..5a7464686de9 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ExpressionUtils.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/ExpressionUtils.java @@ -138,7 +138,7 @@ public class ExpressionUtils { return false; } final PsiType type = castType.getType(); - return TypeUtils.typeEquals("java.lang.String", type); + return TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, type); } return false; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/InheritanceUtil.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/InheritanceUtil.java index 6e747c2699f4..54d4edd52328 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/InheritanceUtil.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/InheritanceUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2006 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.psiutils; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiModifier; import com.intellij.psi.PsiTypeParameter; @@ -45,11 +46,11 @@ public class InheritanceUtil{ } final String className = class1.getQualifiedName(); - if("java.lang.Object".equals(className)){ + if(CommonClassNames.JAVA_LANG_OBJECT.equals(className)){ return true; } final String class2Name = class2.getQualifiedName(); - if("java.lang.Object".equals(class2Name)){ + if(CommonClassNames.JAVA_LANG_OBJECT.equals(class2Name)){ return true; } if(class1.isInheritor(class2, true) || @@ -61,10 +62,10 @@ public class InheritanceUtil{ final Query search = ClassInheritorsSearch.search(class1, scope, true, true); return !search.forEach(new Processor() { - @Override - public boolean process(PsiClass inheritor) { - return !inheritor.equals(class2) && !inheritor.isInheritor(class2, true); - } + public boolean process(PsiClass inheritor) { + return !inheritor.equals(class2) && + !inheritor.isInheritor(class2, true); + } }); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/IteratorUtils.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/IteratorUtils.java index 43b1a3b3990d..2be1ad75404d 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/IteratorUtils.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/IteratorUtils.java @@ -52,11 +52,11 @@ public class IteratorUtils { public static boolean isCallToHasNext( PsiMethodCallExpression methodCallExpression) { return MethodCallUtils.isCallToMethod(methodCallExpression, - "java.util.Iterator", PsiType.BOOLEAN, "hasNext"); + CommonClassNames.JAVA_UTIL_ITERATOR, PsiType.BOOLEAN, "hasNext"); } public static boolean isIterator(PsiClass aClass) { - return ClassUtils.isSubclass(aClass, "java.util.Iterator"); + return ClassUtils.isSubclass(aClass, CommonClassNames.JAVA_UTIL_ITERATOR); } private static class CallsIteratorNextVisitor @@ -91,12 +91,12 @@ public class IteratorUtils { super.visitMethodCallExpression(expression); if (checkScanner) { if (!MethodCallUtils.isCallToMethod(expression, - "java.util.Iterator", null, SCANNER_PATTERN)) { + CommonClassNames.JAVA_UTIL_ITERATOR, null, SCANNER_PATTERN)) { return; } } else { if (!MethodCallUtils.isCallToMethod(expression, - "java.util.Iterator", null, + CommonClassNames.JAVA_UTIL_ITERATOR, null, HardcodedMethodConstants.NEXT)) { return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/MethodCallUtils.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/MethodCallUtils.java index 2c07b7c1830f..e2336c3313fd 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/MethodCallUtils.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/MethodCallUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -263,7 +263,7 @@ public class MethodCallUtils { return false; } final String className = containingClass.getQualifiedName(); - return "java.lang.String".equals(className) || + return CommonClassNames.JAVA_LANG_STRING.equals(className) || "java.util.regex.Pattern".equals(className); } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/SerializationUtils.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/SerializationUtils.java index 7ff931942b5b..445d2f1a95a5 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/SerializationUtils.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/SerializationUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2006 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,26 +28,30 @@ public class SerializationUtils { } public static boolean isSerializable(@Nullable PsiClass aClass) { - return ClassUtils.isSubclass(aClass, "java.io.Serializable"); + return ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_IO_SERIALIZABLE); } public static boolean isExternalizable(@Nullable PsiClass aClass) { - return ClassUtils.isSubclass(aClass, "java.io.Externalizable"); + return ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_IO_EXTERNALIZABLE); } public static boolean isDirectlySerializable(@NotNull PsiClass aClass) { final PsiReferenceList implementsList = aClass.getImplementsList(); - if (implementsList != null) { - final PsiJavaCodeReferenceElement[] interfaces = - implementsList.getReferenceElements(); - for (PsiJavaCodeReferenceElement aInterfaces : interfaces) { - final PsiClass implemented = (PsiClass) aInterfaces.resolve(); - if (implemented != null) { - final String name = implemented.getQualifiedName(); - if ("java.io.Serializable".equals(name)) { - return true; - } - } + if (implementsList == null) { + return false; + } + final PsiJavaCodeReferenceElement[] interfaces = + implementsList.getReferenceElements(); + for (PsiJavaCodeReferenceElement aInterfaces : interfaces) { + final PsiClass implemented = (PsiClass) aInterfaces.resolve(); + if (implemented == null) { + continue; + } + final String name = implemented.getQualifiedName(); + if (CommonClassNames.JAVA_IO_SERIALIZABLE.equals(name)) { + return true; } } return false; @@ -75,9 +79,9 @@ public class SerializationUtils { } public static boolean isReadObject(@NotNull PsiMethod method) { - final PsiManager manager = method.getManager(); - final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); final Project project = method.getProject(); + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); + final PsiElementFactory factory = psiFacade.getElementFactory(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiClassType type = factory.createTypeByFQClassName( "java.io.ObjectInputStream", scope); @@ -86,9 +90,9 @@ public class SerializationUtils { } public static boolean isWriteObject(@NotNull PsiMethod method) { - final PsiManager manager = method.getManager(); - final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); final Project project = method.getProject(); + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); + final PsiElementFactory factory = psiFacade.getElementFactory(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiClassType type = factory.createTypeByFQClassName( "java.io.ObjectOutputStream", scope); @@ -97,14 +101,14 @@ public class SerializationUtils { } public static boolean isReadResolve(@NotNull PsiMethod method) { - return MethodUtils.simpleMethodMatches(method, null, "java.lang.Object", - "readResolve"); + return MethodUtils.simpleMethodMatches(method, null, + CommonClassNames.JAVA_LANG_OBJECT, "readResolve"); } public static boolean isWriteReplace(@NotNull PsiMethod method) { - return MethodUtils.simpleMethodMatches(method, null, "java.lang.Object", - "writeReplace"); + return MethodUtils.simpleMethodMatches(method, null, + CommonClassNames.JAVA_LANG_OBJECT, "writeReplace"); } public static boolean isProbablySerializable(PsiType type) { @@ -115,7 +119,8 @@ public class SerializationUtils { return true; } if (type instanceof PsiArrayType) { - final PsiType componentType = ((PsiArrayType) type).getComponentType(); + final PsiArrayType arrayType = (PsiArrayType) type; + final PsiType componentType = arrayType.getComponentType(); return isProbablySerializable(componentType); } if (type instanceof PsiClassType) { @@ -127,8 +132,10 @@ public class SerializationUtils { if (isExternalizable(psiClass)) { return true; } - if (ClassUtils.isSubclass(psiClass, "java.util.Collection") || - ClassUtils.isSubclass(psiClass, "java.util.Map")) { + if (ClassUtils.isSubclass(psiClass, + CommonClassNames.JAVA_UTIL_COLLECTION) || + ClassUtils.isSubclass(psiClass, + CommonClassNames.JAVA_UTIL_MAP)) { final PsiType[] parameters = classTYpe.getParameters(); for (PsiType parameter : parameters) { if (!isProbablySerializable(parameter)) { diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/SingletonUtil.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/SingletonUtil.java index 19980f61a460..852ea4a333ff 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/SingletonUtil.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/SingletonUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2005 Dave Griffith + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,61 +16,128 @@ package com.siyeh.ig.psiutils; import com.intellij.psi.*; +import com.intellij.psi.search.searches.MethodReferencesSearch; +import com.intellij.util.Processor; +import com.intellij.util.Query; import org.jetbrains.annotations.NotNull; public class SingletonUtil { - private SingletonUtil() { - super(); - } + + private SingletonUtil() {} public static boolean isSingleton(@NotNull PsiClass aClass) { - if (aClass.isInterface() || aClass.isEnum() || aClass.isAnnotationType()) { + if (aClass.isInterface() || aClass.isEnum() || + aClass.isAnnotationType()) { return false; } if(aClass instanceof PsiTypeParameter || aClass instanceof PsiAnonymousClass){ return false; - } - if (!hasConstructor(aClass)) { + } + final PsiMethod[] constructors = getIfOnlyInvisibleConstructors(aClass); + if (constructors.length == 0) { return false; } - if (hasVisibleConstructor(aClass)) { + final PsiField selfInstance = getIfOneStaticSelfInstance(aClass); + if (selfInstance == null) { return false; } - return containsOneStaticSelfInstance(aClass); + return newOnlyAssignsToStaticSelfInstance(constructors[0], selfInstance); } - private static boolean containsOneStaticSelfInstance(PsiClass aClass) { + private static PsiField getIfOneStaticSelfInstance(PsiClass aClass) { final PsiField[] fields = aClass.getFields(); - int numSelfInstances = 0; + PsiField result = null; for(final PsiField field : fields){ final String className = aClass.getQualifiedName(); - if(field.hasModifierProperty(PsiModifier.STATIC)){ - final PsiType type = field.getType(); - final String fieldTypeName = type.getCanonicalText(); - if(fieldTypeName.equals(className)){ - numSelfInstances++; - } + if (!field.hasModifierProperty(PsiModifier.STATIC)) { + continue; } + final PsiType type = field.getType(); + final String fieldTypeName = type.getCanonicalText(); + if (!fieldTypeName.equals(className)) { + continue; + } + if (result != null) { + return null; + } + result = field; } - return numSelfInstances == 1; + return result; } - private static boolean hasConstructor(PsiClass aClass) { - return aClass.getConstructors().length>0; - } - - private static boolean hasVisibleConstructor(PsiClass aClass) { - final PsiMethod[] methods = aClass.getConstructors(); - for(final PsiMethod method : methods){ - if(method.hasModifierProperty(PsiModifier.PUBLIC)){ - return true; + private static PsiMethod[] getIfOnlyInvisibleConstructors(PsiClass aClass) { + final PsiMethod[] constructors = aClass.getConstructors(); + if (constructors.length == 0) { + return PsiMethod.EMPTY_ARRAY; + } + for(final PsiMethod constructor : constructors){ + if(constructor.hasModifierProperty(PsiModifier.PUBLIC)){ + return PsiMethod.EMPTY_ARRAY; } - if(!method.hasModifierProperty(PsiModifier.PRIVATE) && - !method.hasModifierProperty(PsiModifier.PROTECTED)){ - return true; + if(!constructor.hasModifierProperty(PsiModifier.PRIVATE) && + !constructor.hasModifierProperty(PsiModifier.PROTECTED)){ + return PsiMethod.EMPTY_ARRAY; } } - return false; + return constructors; + } + + private static boolean newOnlyAssignsToStaticSelfInstance( + PsiMethod method, final PsiField field) { + final Query search = + MethodReferencesSearch.search(method, field.getUseScope(), + false); + final NewOnlyAssignedToFieldProcessor processor = + new NewOnlyAssignedToFieldProcessor(field); + search.forEach(processor); + return processor.isNewOnlyAssignedToField(); + } + + private static class NewOnlyAssignedToFieldProcessor + implements Processor { + + private boolean newOnlyAssignedToField = true; + private final PsiField field; + + public NewOnlyAssignedToFieldProcessor(PsiField field) { + this.field = field; + } + + public boolean process(PsiReference reference) { + final PsiElement element = reference.getElement(); + final PsiElement parent = element.getParent(); + if (!(parent instanceof PsiNewExpression)) { + newOnlyAssignedToField = false; + return false; + } + final PsiElement grandParent = parent.getParent(); + if (field.equals(grandParent)) { + return true; + } + if (!(grandParent instanceof PsiAssignmentExpression)) { + newOnlyAssignedToField = false; + return false; + } + final PsiAssignmentExpression assignmentExpression = + (PsiAssignmentExpression) grandParent; + final PsiExpression lhs = assignmentExpression.getLExpression(); + if (!(lhs instanceof PsiReferenceExpression)) { + newOnlyAssignedToField = false; + return false; + } + final PsiReferenceExpression referenceExpression = + (PsiReferenceExpression) lhs; + final PsiElement target = referenceExpression.resolve(); + if (!field.equals(target)) { + newOnlyAssignedToField = false; + return false; + } + return true; + } + + public boolean isNewOnlyAssignedToField() { + return newOnlyAssignedToField; + } } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/TypeUtils.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/TypeUtils.java index 419d29c34b7f..3bf1c26e149e 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/TypeUtils.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/TypeUtils.java @@ -53,15 +53,15 @@ public class TypeUtils { public static PsiClassType getJavaLangObjectType( @NotNull PsiElement context) { - return getType("java.lang.Object", context); + return getType(CommonClassNames.JAVA_LANG_OBJECT, context); } public static boolean isJavaLangObject(@Nullable PsiType targetType) { - return typeEquals("java.lang.Object", targetType); + return typeEquals(CommonClassNames.JAVA_LANG_OBJECT, targetType); } public static boolean isJavaLangString(@Nullable PsiType targetType) { - return typeEquals("java.lang.String", targetType); + return typeEquals(CommonClassNames.JAVA_LANG_STRING, targetType); } public static boolean expressionHasTypeOrSubtype( diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/WeakestTypeFinder.java b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/WeakestTypeFinder.java index 280e6c5545c2..cc77743d1be4 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/WeakestTypeFinder.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/psiutils/WeakestTypeFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2009 Bas Leijdekkers + * Copyright 2008-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.Query; import com.siyeh.HardcodedMethodConstants; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -69,7 +70,7 @@ public class WeakestTypeFinder { final Project project = manager.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final PsiClass javaLangObjectClass = - facade.findClass("java.lang.Object", scope); + facade.findClass(CommonClassNames.JAVA_LANG_OBJECT, scope); if (javaLangObjectClass == null || variableOrMethodClass.equals(javaLangObjectClass)) { return Collections.emptyList(); @@ -128,11 +129,12 @@ public class WeakestTypeFinder { } else if (referenceParent instanceof PsiForeachStatement) { final PsiForeachStatement foreachStatement = (PsiForeachStatement)referenceParent; - if (foreachStatement.getIteratedValue() != referenceElement) { + if (!foreachStatement.getIteratedValue().equals(referenceElement)) { return Collections.emptyList(); } final PsiClass javaLangIterableClass = - facade.findClass("java.lang.Iterable", scope); + facade.findClass(CommonClassNames.JAVA_LANG_ITERABLE, + scope); if (javaLangIterableClass == null) { return Collections.emptyList(); } @@ -293,7 +295,7 @@ public class WeakestTypeFinder { if (!useParameterizedTypeForCollectionMethods) { return checkType(type, substitutor, weakestTypeClasses); } - final String methodName = method.getName(); + @NonNls final String methodName = method.getName(); if (HardcodedMethodConstants.REMOVE.equals(methodName) || HardcodedMethodConstants.GET.equals(methodName) || "containsKey".equals(methodName) || @@ -303,8 +305,9 @@ public class WeakestTypeFinder { HardcodedMethodConstants.LAST_INDEX_OF.equals(methodName)) { final PsiClass containingClass = method.getContainingClass(); if (ClassUtils.isSubclass(containingClass, - "java.util.Map") || ClassUtils.isSubclass(containingClass, - "java.util.Collection")) { + CommonClassNames.JAVA_UTIL_MAP) || + ClassUtils.isSubclass(containingClass, + CommonClassNames.JAVA_UTIL_COLLECTION)) { final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); final PsiExpression qualifier = @@ -467,7 +470,7 @@ public class WeakestTypeFinder { throwStatement.getResolveScope()); final PsiClass runtimeExceptionClass = runtimeExceptionType.resolve(); if (runtimeExceptionClass != null && - com.intellij.psi.util.InheritanceUtil.isInheritorOrSelf(variableOrMethodClass, + InheritanceUtil.isInheritorOrSelf(variableOrMethodClass, runtimeExceptionClass, true)) { if (!checkType(runtimeExceptionType, weakestTypeClasses)) { return false; @@ -518,9 +521,9 @@ public class WeakestTypeFinder { return true; } if (!ClassUtils.isSubclass(aClass, - "java.lang.RuntimeException") && + CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION) && !ClassUtils.isSubclass(aClass, - "java.lang.Error")) { + CommonClassNames.JAVA_LANG_ERROR)) { return true; } @@ -579,8 +582,11 @@ public class WeakestTypeFinder { } private static void checkClass( - @NotNull PsiClass aClass, + @Nullable PsiClass aClass, @NotNull Collection weakestTypeClasses) { + if (aClass == null) { + return; + } boolean shouldAdd = true; for (Iterator iterator = weakestTypeClasses.iterator(); iterator.hasNext();) { @@ -636,6 +642,9 @@ public class WeakestTypeFinder { return false; } final PsiClass containingClass = method.getContainingClass(); + if (containingClass == null) { + return false; + } if (method.hasModifierProperty(PsiModifier.PROTECTED)) { if (referencingClass.isInheritor(containingClass, true)) { return true; diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/security/JDBCExecuteWithNonConstantStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/security/JDBCExecuteWithNonConstantStringInspection.java index 2869a574fc32..9672698927fb 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/security/JDBCExecuteWithNonConstantStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/security/JDBCExecuteWithNonConstantStringInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,18 +44,21 @@ public class JDBCExecuteWithNonConstantStringInspection } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "jdbc.execute.with.non.constant.string.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "jdbc.execute.with.non.constant.string.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new RuntimeExecVisitor(); } @@ -93,7 +96,7 @@ public class JDBCExecuteWithNonConstantStringInspection return; } final String typeText = type.getCanonicalText(); - if (!"java.lang.String".equals(typeText)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(typeText)) { return; } final String stringValue = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/security/JDBCPrepareStatementWithNonConstantStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/security/JDBCPrepareStatementWithNonConstantStringInspection.java index e40f4a222780..45e7be17045b 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/security/JDBCPrepareStatementWithNonConstantStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/security/JDBCPrepareStatementWithNonConstantStringInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,18 +42,21 @@ public class JDBCPrepareStatementWithNonConstantStringInspection } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "jdbc.prepare.statement.with.non.constant.string.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "jdbc.prepare.statement.with.non.constant.string.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new RuntimeExecVisitor(); } @@ -91,7 +94,7 @@ public class JDBCPrepareStatementWithNonConstantStringInspection return; } final String typeText = type.getCanonicalText(); - if (!"java.lang.String".equals(typeText)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(typeText)) { return; } final String stringValue = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/security/LoadLibraryWithNonConstantStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/security/LoadLibraryWithNonConstantStringInspection.java index e38450cab439..aa7d1882eb3a 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/security/LoadLibraryWithNonConstantStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/security/LoadLibraryWithNonConstantStringInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,18 +27,21 @@ import org.jetbrains.annotations.NotNull; public class LoadLibraryWithNonConstantStringInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "load.library.with.non.constant.string.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "load.library.with.non.constant.string.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new RuntimeExecVisitor(); } @@ -77,7 +80,7 @@ public class LoadLibraryWithNonConstantStringInspection return; } final String typeText = type.getCanonicalText(); - if (!"java.lang.String".equals(typeText)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(typeText)) { return; } final String stringValue = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/security/RuntimeExecWithNonConstantStringInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/security/RuntimeExecWithNonConstantStringInspection.java index 867049b10654..e60b77658f93 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/security/RuntimeExecWithNonConstantStringInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/security/RuntimeExecWithNonConstantStringInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,23 +26,27 @@ import org.jetbrains.annotations.NotNull; public class RuntimeExecWithNonConstantStringInspection extends BaseInspection { + @Override @NotNull public String getID() { return "CallToRuntimeExecWithNonConstantString"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "runtime.exec.call.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "runtime.exec.with.non.constant.string.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new RuntimeExecVisitor(); } @@ -82,7 +86,7 @@ public class RuntimeExecWithNonConstantStringInspection return; } final String typeText = type.getCanonicalText(); - if (!"java.lang.String".equals(typeText)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(typeText)) { return; } final String stringValue = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/security/SystemPropertiesInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/security/SystemPropertiesInspection.java index 6286bd7f9ddb..0a89463e9e74 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/security/SystemPropertiesInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/security/SystemPropertiesInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,7 @@ */ package com.siyeh.ig.security; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiMethodCallExpression; -import com.intellij.psi.PsiReferenceExpression; +import com.intellij.psi.*; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; @@ -27,17 +24,20 @@ import org.jetbrains.annotations.NotNull; public class SystemPropertiesInspection extends BaseInspection { + @Override @NotNull public String getID() { return "AccessOfSystemProperties"; } + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "system.properties.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { final boolean isGetSystemProperty = @@ -56,6 +56,7 @@ public class SystemPropertiesInspection extends BaseInspection { } } + @Override public BaseInspectionVisitor buildVisitor() { return new SystemSetSecurityManagerVisitor(); } @@ -128,7 +129,7 @@ public class SystemPropertiesInspection extends BaseInspection { if (className == null) { return false; } - return "java.lang.Integer".equals(className); + return CommonClassNames.JAVA_LANG_INTEGER.equals(className); } private static boolean isBooleanGetBoolean( @@ -152,7 +153,7 @@ public class SystemPropertiesInspection extends BaseInspection { if (className == null) { return false; } - return "java.lang.Boolean".equals(className); + return CommonClassNames.JAVA_LANG_BOOLEAN.equals(className); } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/ComparatorNotSerializableInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/ComparatorNotSerializableInspection.java index 15d188bb5a5c..382f61343232 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/ComparatorNotSerializableInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/ComparatorNotSerializableInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2006-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.siyeh.ig.serialization; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiAnonymousClass; import com.intellij.psi.PsiClass; import com.siyeh.InspectionGadgetsBundle; @@ -29,23 +30,27 @@ import org.jetbrains.annotations.Nullable; public class ComparatorNotSerializableInspection extends BaseInspection { + @Override @NotNull public String getDisplayName(){ return InspectionGadgetsBundle.message( "comparator.not.serializable.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos){ return InspectionGadgetsBundle.message( "comparator.not.serializable.problem.descriptor"); } + @Override @Nullable protected InspectionGadgetsFix buildFix(Object... infos) { return new MakeSerializableFix(); } + @Override public BaseInspectionVisitor buildVisitor(){ return new ComparatorNotSerializableVisitor(); } @@ -58,7 +63,8 @@ public class ComparatorNotSerializableInspection extends BaseInspection { if (aClass instanceof PsiAnonymousClass) { return; } - if (!ClassUtils.isSubclass(aClass, "java.util.Comparator")) { + if (!ClassUtils.isSubclass(aClass, + CommonClassNames.JAVA_UTIL_COMPARATOR)) { return; } if (SerializationUtils.isSerializable(aClass)) { diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/NonSerializableObjectBoundToHttpSessionInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/NonSerializableObjectBoundToHttpSessionInspection.java index 84b5e783e940..5fafce6b45ba 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/NonSerializableObjectBoundToHttpSessionInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/NonSerializableObjectBoundToHttpSessionInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2006-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,7 @@ */ package com.siyeh.ig.serialization; -import com.intellij.psi.PsiExpression; -import com.intellij.psi.PsiExpressionList; -import com.intellij.psi.PsiMethodCallExpression; -import com.intellij.psi.PsiType; +import com.intellij.psi.*; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; @@ -29,18 +26,21 @@ import org.jetbrains.annotations.NotNull; public class NonSerializableObjectBoundToHttpSessionInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "non.serializable.object.bound.to.http.session.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "non.serializable.object.bound.to.http.session.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new NonSerializableObjectBoundToHttpSessionVisitor(); } @@ -53,11 +53,12 @@ public class NonSerializableObjectBoundToHttpSessionInspection super.visitMethodCallExpression(methodCallExpression); if (!MethodCallUtils.isSimpleCallToMethod(methodCallExpression, "javax.servlet.http.HttpSession", PsiType.VOID, - "putValue", "java.lang.String", "java.lang.Object") && + "putValue", CommonClassNames.JAVA_LANG_STRING, + CommonClassNames.JAVA_LANG_OBJECT) && !MethodCallUtils.isSimpleCallToMethod(methodCallExpression, "javax.servlet.http.HttpSession", PsiType.VOID, - "setAttribute", "java.lang.String", - "java.lang.Object")) { + "setAttribute", CommonClassNames.JAVA_LANG_STRING, + CommonClassNames.JAVA_LANG_OBJECT)) { return; } final PsiExpressionList argumentList = diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/NonSerializableObjectPassedToObjectStreamInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/NonSerializableObjectPassedToObjectStreamInspection.java index fbdadf254ae6..7aa0eff3c528 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/NonSerializableObjectPassedToObjectStreamInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/serialization/NonSerializableObjectPassedToObjectStreamInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2006-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,7 @@ */ package com.siyeh.ig.serialization; -import com.intellij.psi.PsiExpression; -import com.intellij.psi.PsiExpressionList; -import com.intellij.psi.PsiMethodCallExpression; -import com.intellij.psi.PsiType; +import com.intellij.psi.*; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; @@ -29,18 +26,21 @@ import org.jetbrains.annotations.NotNull; public class NonSerializableObjectPassedToObjectStreamInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "non.serializable.object.passed.to.object.stream.display.name"); } + @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "non.serializable.object.passed.to.object.stream.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new NonSerializableObjectPassedToObjectStreamVisitor(); } @@ -53,24 +53,25 @@ public class NonSerializableObjectPassedToObjectStreamInspection super.visitMethodCallExpression(methodCallExpression); if (!MethodCallUtils.isSimpleCallToMethod(methodCallExpression, - "java.io.ObjectOutputStream", - PsiType.VOID, "writeObject", "java.lang.Object")) { + "java.io.ObjectOutputStream", PsiType.VOID, "writeObject", + CommonClassNames.JAVA_LANG_OBJECT)) { return; } - final PsiExpressionList argList = + final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); - final PsiExpression[] args = argList.getExpressions(); - if(args.length!=1) { + final PsiExpression[] arguments = argumentList.getExpressions(); + if (arguments.length != 1) { return; } - final PsiType argType = args[0].getType(); - if(argType == null) { + final PsiExpression argument = arguments[0]; + final PsiType argumentType = argument.getType(); + if (argumentType == null) { return; } - if (SerializationUtils.isProbablySerializable(argType)) { + if (SerializationUtils.isProbablySerializable(argumentType)) { return; } - registerError(args[0]); + registerError(argument); } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/CallToStringConcatCanBeReplacedByOperatorInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/CallToStringConcatCanBeReplacedByOperatorInspection.java index 213bacd37f7c..bee51f704609 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/CallToStringConcatCanBeReplacedByOperatorInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/CallToStringConcatCanBeReplacedByOperatorInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 Bas Leijdekkers + * Copyright 2007-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,7 @@ import org.jetbrains.annotations.Nullable; public class CallToStringConcatCanBeReplacedByOperatorInspection extends BaseInspection { + @Override @Nls @NotNull public String getDisplayName() { @@ -39,17 +40,20 @@ public class CallToStringConcatCanBeReplacedByOperatorInspection "call.to.string.concat.can.be.replaced.by.operator.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "call.to.string.concat.can.be.replaced.by.operator.problem.descriptor"); } + @Override @Nullable protected InspectionGadgetsFix buildFix(Object... infos) { return new CallToStringConcatCanBeReplacedByOperatorFix(); } + @Override public BaseInspectionVisitor buildVisitor() { return new CallToStringConcatCanBeReplacedByOperatorVisitor(); } @@ -62,6 +66,7 @@ public class CallToStringConcatCanBeReplacedByOperatorInspection return InspectionGadgetsBundle.message("call.to.string.concat.can.be.replaced.by.operator.quickfix"); } + @Override protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); @@ -91,7 +96,7 @@ public class CallToStringConcatCanBeReplacedByOperatorInspection final PsiExpression argument = arguments[0]; @NonNls final String newExpression = - qualifier.getText() + "+" + argument.getText(); + qualifier.getText() + '+' + argument.getText(); replaceExpression(methodCallExpression, newExpression); } } @@ -102,15 +107,18 @@ public class CallToStringConcatCanBeReplacedByOperatorInspection @Override public void visitMethodCallExpression( PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); - final PsiManager manager = expression.getManager(); - final PsiClass stringClass = - JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.String", expression.getResolveScope()); + final Project project = expression.getProject(); + final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); + final PsiClass stringClass = + psiFacade.findClass(CommonClassNames.JAVA_LANG_STRING, + expression.getResolveScope()); if (stringClass == null) { return; } final PsiClassType stringType = - JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createType(stringClass); - if (!MethodCallUtils.isCallToMethod(expression, "java.lang.String", + psiFacade.getElementFactory().createType(stringClass); + if (!MethodCallUtils.isCallToMethod(expression, + CommonClassNames.JAVA_LANG_STRING, stringType, "concat", stringType)) { return; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ConfusingOctalEscapeInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ConfusingOctalEscapeInspection.java index 34938533051b..0d66427211b8 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ConfusingOctalEscapeInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ConfusingOctalEscapeInspection.java @@ -15,6 +15,7 @@ */ package com.siyeh.ig.style; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiLiteralExpression; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; @@ -55,7 +56,8 @@ public class ConfusingOctalEscapeInspection extends BaseInspection { @Override public void visitLiteralExpression( @NotNull PsiLiteralExpression expression) { super.visitLiteralExpression(expression); - if (!TypeUtils.expressionHasType(expression, "java.lang.String")) { + if (!TypeUtils.expressionHasType(expression, + CommonClassNames.JAVA_LANG_STRING)) { return; } final String text = expression.getText(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/EqualsCalledOnEnumConstantInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/EqualsCalledOnEnumConstantInspection.java index b8b5d60a6708..a20635f42967 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/EqualsCalledOnEnumConstantInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/EqualsCalledOnEnumConstantInspection.java @@ -142,7 +142,7 @@ public class EqualsCalledOnEnumConstantInspection extends BaseInspection { final PsiExpression qualifier = methodExpression.getQualifierExpression(); if (!TypeUtils.expressionHasTypeOrSubtype(qualifier, - "java.lang.Enum")) { + CommonClassNames.JAVA_LANG_ENUM)) { return; } registerMethodCallError(expression, expression); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ExtendsObjectInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ExtendsObjectInspection.java index 452b30206584..0b95a30b94aa 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ExtendsObjectInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ExtendsObjectInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,26 +27,31 @@ import org.jetbrains.annotations.NotNull; public class ExtendsObjectInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message("extends.object.display.name"); } + @Override @NotNull public String getID() { return "ClassExplicitlyExtendsObject"; } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "extends.object.problem.descriptor"); } + @Override public boolean isEnabledByDefault() { return true; } + @Override protected InspectionGadgetsFix buildFix(Object... infos) { return new ExtendsObjectFix(); } @@ -59,6 +64,7 @@ public class ExtendsObjectInspection extends BaseInspection { "extends.object.remove.quickfix"); } + @Override public void doFix(@NotNull Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement extendClassIdentifier = descriptor.getPsiElement(); @@ -80,6 +86,7 @@ public class ExtendsObjectInspection extends BaseInspection { } } + @Override public BaseInspectionVisitor buildVisitor() { return new ExtendsObjectVisitor(); } @@ -95,7 +102,7 @@ public class ExtendsObjectInspection extends BaseInspection { } final PsiClassType[] types = aClass.getExtendsListTypes(); for (final PsiClassType type : types){ - if (type.equalsToText("java.lang.Object")){ + if (type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)){ registerClassError(aClass); } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ImplicitCallToSuperInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ImplicitCallToSuperInspection.java index 2e4862264347..20d592f9fbbe 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ImplicitCallToSuperInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ImplicitCallToSuperInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,22 +34,26 @@ public class ImplicitCallToSuperInspection extends BaseInspection { @SuppressWarnings("PublicField") public boolean m_ignoreForObjectSubclasses = false; + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "implicit.call.to.super.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "implicit.call.to.super.problem.descriptor"); } + @Override public InspectionGadgetsFix buildFix(Object... infos) { return new AddExplicitSuperCall(); } + @Override public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message( "implicit.call.to.super.ignore.option"), @@ -64,6 +68,7 @@ public class ImplicitCallToSuperInspection extends BaseInspection { "implicit.call.to.super.make.explicit.quickfix"); } + @Override public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement methodName = descriptor.getPsiElement(); @@ -72,10 +77,11 @@ public class ImplicitCallToSuperInspection extends BaseInspection { return; } final PsiCodeBlock body = method.getBody(); - final PsiManager psiManager = PsiManager.getInstance(project); - final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); + final PsiElementFactory factory = + JavaPsiFacade.getElementFactory(project); final PsiStatement newStatement = factory.createStatementFromText("super();", null); + final PsiManager psiManager = PsiManager.getInstance(project); final CodeStyleManager styleManager = psiManager.getCodeStyleManager(); if (body == null) { @@ -87,6 +93,7 @@ public class ImplicitCallToSuperInspection extends BaseInspection { } } + @Override public BaseInspectionVisitor buildVisitor() { return new ImplicitCallToSuperVisitor(); } @@ -109,7 +116,7 @@ public class ImplicitCallToSuperInspection extends BaseInspection { final PsiClass superClass = containingClass.getSuperClass(); if (superClass != null) { final String superClassName = superClass.getQualifiedName(); - if ("java.lang.Object".equals(superClassName)) { + if (CommonClassNames.JAVA_LANG_OBJECT.equals(superClassName)) { return; } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ListIndexOfReplaceableByContainsInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ListIndexOfReplaceableByContainsInspection.java index 5e4b8c975ec7..4a312fac4cdf 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ListIndexOfReplaceableByContainsInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ListIndexOfReplaceableByContainsInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2009 Bas Leijdekkers + * Copyright 2006-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -235,7 +235,8 @@ public class ListIndexOfReplaceableByContainsInspection GlobalSearchScope.allScope(project); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass javaUtilListClass = - psiFacade.findClass("java.util.List", projectScope); + psiFacade.findClass(CommonClassNames.JAVA_UTIL_LIST, + projectScope); if (javaUtilListClass == null) { return false; } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/RedundantImplementsInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/RedundantImplementsInspection.java index bea7b21e8334..f09a33d95496 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/RedundantImplementsInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/RedundantImplementsInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2009 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,10 +18,7 @@ package com.siyeh.ig.style; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel; import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiJavaCodeReferenceElement; -import com.intellij.psi.PsiReferenceList; +import com.intellij.psi.*; import com.intellij.util.IncorrectOperationException; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; @@ -33,7 +30,9 @@ import javax.swing.*; public class RedundantImplementsInspection extends BaseInspection { + @SuppressWarnings({"PublicField"}) public boolean ignoreSerializable = false; + @SuppressWarnings({"PublicField"}) public boolean ignoreCloneable = false; @Override @@ -154,10 +153,12 @@ public class RedundantImplementsInspection extends BaseInspection { PsiJavaCodeReferenceElement[] implementsElements) { final String qualifiedName = implementedClass.getQualifiedName(); if (ignoreSerializable && - "java.io.Serializable".equals(qualifiedName)) { + CommonClassNames.JAVA_IO_SERIALIZABLE.equals( + qualifiedName)) { return; } else if (ignoreCloneable && - "java.lang.Cloneable".equals(qualifiedName)) { + CommonClassNames.JAVA_LANG_CLONEABLE.equals( + qualifiedName)) { return; } for (final PsiJavaCodeReferenceElement extendsElement : diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/TypeParameterExtendsObjectInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/TypeParameterExtendsObjectInspection.java index 1cc87096af0e..16e18343b148 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/TypeParameterExtendsObjectInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/TypeParameterExtendsObjectInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,17 +29,20 @@ import org.jetbrains.annotations.NotNull; public class TypeParameterExtendsObjectInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "type.parameter.extends.object.display.name"); } + @Override @NotNull public String getID() { return "TypeParameterExplicitlyExtendsObject"; } + @Override @NotNull protected String buildErrorString(Object... infos) { final Integer type = (Integer) infos[0]; @@ -52,10 +55,12 @@ public class TypeParameterExtendsObjectInspection extends BaseInspection { } } + @Override public boolean isEnabledByDefault() { return true; } + @Override protected InspectionGadgetsFix buildFix(Object... infos) { return new ExtendsObjectFix(); } @@ -68,6 +73,7 @@ public class TypeParameterExtendsObjectInspection extends BaseInspection { "extends.object.remove.quickfix"); } + @Override public void doFix(@NotNull Project project, ProblemDescriptor descriptor) throws IncorrectOperationException{ @@ -116,7 +122,7 @@ public class TypeParameterExtendsObjectInspection extends BaseInspection { return; } final PsiClassType extendsType = extendsListTypes[0]; - if (!extendsType.equalsToText("java.lang.Object")) { + if (!extendsType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { return; } final PsiIdentifier nameIdentifier = parameter.getNameIdentifier(); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryCallToStringValueOfInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryCallToStringValueOfInspection.java index 75c385fe1290..68979f1eb550 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryCallToStringValueOfInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/UnnecessaryCallToStringValueOfInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2008 Bas Leijdekkers + * Copyright 2008-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -111,17 +111,20 @@ public class UnnecessaryCallToStringValueOfInspection extends BaseInspection { final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) parent; final PsiType type = binaryExpression.getType(); - if (!TypeUtils.typeEquals("java.lang.String", type)) { + if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, + type)) { return; } final PsiExpression lhs = binaryExpression.getLOperand(); if (lhs == expression) { final PsiExpression rhs = binaryExpression.getROperand(); - if (rhs == null || !TypeUtils.typeEquals("java.lang.String", + if (rhs == null || !TypeUtils.typeEquals( + CommonClassNames.JAVA_LANG_STRING, rhs.getType())) { return; } - } else if (!TypeUtils.typeEquals("java.lang.String", lhs.getType())) { + } else if (!TypeUtils.typeEquals(CommonClassNames.JAVA_LANG_STRING, + lhs.getType())) { return; } final PsiExpressionList argumentList = expression.getArgumentList(); @@ -143,8 +146,11 @@ public class UnnecessaryCallToStringValueOfInspection extends BaseInspection { return; } final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } final String qualifiedName = aClass.getQualifiedName(); - if (!"java.lang.String".equals(qualifiedName)) { + if (!CommonClassNames.JAVA_LANG_STRING.equals(qualifiedName)) { return; } registerError(expression, argument); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/threading/AccessToNonThreadSafeStaticFieldFromInstanceInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/threading/AccessToNonThreadSafeStaticFieldFromInstanceInspection.java index d26d7639a06d..4eddde3777be 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/threading/AccessToNonThreadSafeStaticFieldFromInstanceInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/threading/AccessToNonThreadSafeStaticFieldFromInstanceInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 Bas Leijdekkers + * Copyright 2007-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,6 +49,7 @@ public class AccessToNonThreadSafeStaticFieldFromInstanceInspection parseString(nonThreadSafeTypes, nonThreadSafeTypeList); } + @Override @Nls @NotNull public String getDisplayName() { @@ -56,6 +57,7 @@ public class AccessToNonThreadSafeStaticFieldFromInstanceInspection "access.to.non.thread.safe.static.field.from.instance.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { if (infos[0] instanceof PsiMethod) { @@ -68,22 +70,26 @@ public class AccessToNonThreadSafeStaticFieldFromInstanceInspection infos[1]); } + @Override @Nullable public JComponent createOptionsPanel() { final Form form = new Form(); return form.getContentPanel(); } + @Override public void readSettings(Element node) throws InvalidDataException { super.readSettings(node); parseString(nonThreadSafeTypes, nonThreadSafeTypeList); } + @Override public void writeSettings(Element node) throws WriteExternalException { nonThreadSafeTypes = formatString(nonThreadSafeTypeList); super.writeSettings(node); } + @Override public BaseInspectionVisitor buildVisitor() { return new AccessToNonThreadSafeStaticFieldFromInstanceVisitor(); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/threading/CallToNativeMethodWhileLockedInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/threading/CallToNativeMethodWhileLockedInspection.java index 53223ab2671c..c1514914b134 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/threading/CallToNativeMethodWhileLockedInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/threading/CallToNativeMethodWhileLockedInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,7 @@ */ package com.siyeh.ig.threading; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiMethod; -import com.intellij.psi.PsiMethodCallExpression; -import com.intellij.psi.PsiModifier; +import com.intellij.psi.*; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; @@ -28,18 +25,21 @@ import org.jetbrains.annotations.NotNull; public class CallToNativeMethodWhileLockedInspection extends BaseInspection { + @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "call.to.native.method.while.locked.display.name"); } + @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "call.to.native.method.while.locked.problem.descriptor"); } + @Override public BaseInspectionVisitor buildVisitor() { return new CallToNativeMethodWhileLockedVisitor(); } @@ -61,7 +61,7 @@ public class CallToNativeMethodWhileLockedInspection return; } final String className = containingClass.getQualifiedName(); - if ("java.lang.Object".equals(className)) { + if (CommonClassNames.JAVA_LANG_OBJECT.equals(className)) { return; } if (!SynchronizationUtil.isInSynchronizedContext(expression)) { diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/threading/SynchronizedOnLiteralObjectInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/threading/SynchronizedOnLiteralObjectInspection.java index c9fd36e2f393..5cb4338e9836 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/threading/SynchronizedOnLiteralObjectInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/threading/SynchronizedOnLiteralObjectInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2007-2009 Bas Leijdekkers + * Copyright 2007-2010 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,7 +80,7 @@ public class SynchronizedOnLiteralObjectInspection extends BaseInspection { final Project project = expression.getProject(); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass javaLangNumberClass = - psiFacade.findClass("java.lang.Number", + psiFacade.findClass(CommonClassNames.JAVA_LANG_NUMBER, expression.getResolveScope()); if (javaLangNumberClass == null) { return false; @@ -89,9 +89,9 @@ public class SynchronizedOnLiteralObjectInspection extends BaseInspection { psiFacade.getElementFactory(); final PsiClassType javaLangNumberType = elementFactory.createType(javaLangNumberClass); - return type.equalsToText("java.lang.String") || - type.equalsToText("java.lang.Boolean") || - type.equalsToText("java.lang.Character") || + return type.equalsToText(CommonClassNames.JAVA_LANG_STRING) || + type.equalsToText(CommonClassNames.JAVA_LANG_BOOLEAN) || + type.equalsToText(CommonClassNames.JAVA_LANG_CHARACTER) || javaLangNumberType.isAssignableFrom(type); } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/threading/WaitNotInSynchronizedContextInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/threading/WaitNotInSynchronizedContextInspection.java index 26dff5a2bdff..32a3c2c9db2e 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/threading/WaitNotInSynchronizedContextInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/threading/WaitNotInSynchronizedContextInspection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2010 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ public class WaitNotInSynchronizedContextInspection @Override @NotNull protected String buildErrorString(Object... infos) { - final String text; + @NonNls final String text; if (infos.length > 0) { final PsiElement element = (PsiElement)infos[0]; text = element.getText(); @@ -78,8 +78,11 @@ public class WaitNotInSynchronizedContextInspection return; } final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } final String qualifiedName = aClass.getQualifiedName(); - if (!qualifiedName.equals("java.lang.Object")) { + if (!CommonClassNames.JAVA_LANG_OBJECT.equals(qualifiedName)) { return; } final PsiExpression qualifier = diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/classlayout/Singleton.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/classlayout/Singleton.java deleted file mode 100644 index 81ffc1e94669..000000000000 --- a/plugins/InspectionGadgets/test/com/siyeh/igtest/classlayout/Singleton.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.siyeh.igtest.classlayout; - -public class Singleton{ - private static Singleton ourInstance = new Singleton(); - - public static Singleton getInstance(){ - return ourInstance; - } - - private Singleton(){ - } -} diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/classlayout/singleton/Singleton.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/classlayout/singleton/Singleton.java new file mode 100644 index 000000000000..b69113553118 --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/classlayout/singleton/Singleton.java @@ -0,0 +1,40 @@ +package com.siyeh.igtest.classlayout.singleton; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Singleton{ + private static Singleton ourInstance = new Singleton(); + + public static Singleton getInstance(){ + return ourInstance; + } + + private Singleton(){ + } +} +class NonSingleton { + public static final NonSingleton EMPTY = new NonSingleton(Collections.emptyList()); + + private final List values; + + private NonSingleton(List values) { + this.values = values; + } + + public int size() { + return values.size(); + } + + public String get(int index) { + return values.get(index); + } + + //this method makes the class a non-singleton + public NonSingleton add(String s) { + List copy = new ArrayList(values); + copy.add(s); + return new NonSingleton(copy); + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/classlayout/singleton/expected.xml b/plugins/InspectionGadgets/test/com/siyeh/igtest/classlayout/singleton/expected.xml new file mode 100644 index 000000000000..29461237be69 --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/classlayout/singleton/expected.xml @@ -0,0 +1,11 @@ + + + + + Singleton.java + 7 + Singleton + Class <code>Singleton</code> is a singleton #loc + + + \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/errorhandling/toobroadcatch/TooBroadCatchBlock.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/errorhandling/toobroadcatch/TooBroadCatchBlock.java index 688c5e70d46b..2d45b4f42297 100644 --- a/plugins/InspectionGadgets/test/com/siyeh/igtest/errorhandling/toobroadcatch/TooBroadCatchBlock.java +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/errorhandling/toobroadcatch/TooBroadCatchBlock.java @@ -34,4 +34,26 @@ public class TooBroadCatchBlock{ } } + + void bars(boolean a, boolean b, boolean c) { + try { + if (!a) { + throw new NotActiveException(); // extends ObjectStreamException + } + if (b) { + throw new StreamCorruptedException(); // extends ObjectStreamException + } + if (c) { + throw new IOException(); + } + } catch (ObjectStreamException e) { + // Deal with ObjectStreamException (a subclass of IOException)... + } catch (IOException e) { + // Deal with IOException... + } + } + + class ObjectStreamException extends IOException {} + class StreamCorruptedException extends ObjectStreamException {} + class NotActiveException extends ObjectStreamException {} } diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/errorhandling/toobroadcatch/expected.xml b/plugins/InspectionGadgets/test/com/siyeh/igtest/errorhandling/toobroadcatch/expected.xml index 375a3898c5aa..55b425d76f7b 100644 --- a/plugins/InspectionGadgets/test/com/siyeh/igtest/errorhandling/toobroadcatch/expected.xml +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/errorhandling/toobroadcatch/expected.xml @@ -21,4 +21,11 @@ Overly broad 'catch' block Catch of <code>RuntimeException</code> is too broad, masking exception 'NullPointerException' #loc + + + TooBroadCatchBlock.java + 49 + Overly broad 'catch' block + Catch of <code>ObjectStreamException</code> is too broad, masking exceptions 'NotActiveException' and 'StreamCorruptedException' #loc + \ No newline at end of file diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/classlayout/SingletonInspectionTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/classlayout/SingletonInspectionTest.java new file mode 100644 index 000000000000..602525735a2d --- /dev/null +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/classlayout/SingletonInspectionTest.java @@ -0,0 +1,11 @@ +package com.siyeh.ig.classlayout; + +import com.IGInspectionTestCase; + +public class SingletonInspectionTest extends IGInspectionTestCase { + + public void test() throws Exception { + doTest("com/siyeh/igtest/classlayout/singleton", + new SingletonInspection()); + } +} \ No newline at end of file diff --git a/plugins/android/resources/messages/AndroidBundle.properties b/plugins/android/resources/messages/AndroidBundle.properties index 1ab856936ffa..c6ed617734b4 100644 --- a/plugins/android/resources/messages/AndroidBundle.properties +++ b/plugins/android/resources/messages/AndroidBundle.properties @@ -177,7 +177,7 @@ android.facet.editor.is.library.checkbox=Is Library project android.run.sdk.manager.action.text=Android SDK and AVD Manager android.choose.sdk.label=Please choose Android SDK location android.choose.sdk.title=Choose SDK -copy.resources.from.artifacts.setting=Copy resources from Maven artifacts before Make +copy.resources.from.artifacts.setting=Run "process-resources" Maven task before Make android.facet.settings.enable=Enable android.apk.settings.title=Android Packaging Compiler android.create.avd.dialog.sdcard.size=Size: @@ -217,4 +217,5 @@ android.manifest.debuggable.attribute.not.true.warning=The manifest 'debuggable' android.logcat.no.android.facets.error=There is no Android facets in the project android.facet.compiler.settings.manifest.title=Manifest android.facet.settings.compiler.manifest.from.structure=Use AndroidManifest.xml file specified at "Structure" section -android.facet.settings.compiler.manifest.use.custom=Use custom manifest file: \ No newline at end of file +android.facet.settings.compiler.manifest.use.custom=Use custom manifest file: +android.facet.settings.compile.resources.by.ide=Compile resources by IDE \ No newline at end of file diff --git a/plugins/android/src/org/jetbrains/android/compiler/AndroidAptCompiler.java b/plugins/android/src/org/jetbrains/android/compiler/AndroidAptCompiler.java index 41882f0b06fa..d580340c5a9f 100644 --- a/plugins/android/src/org/jetbrains/android/compiler/AndroidAptCompiler.java +++ b/plugins/android/src/org/jetbrains/android/compiler/AndroidAptCompiler.java @@ -56,8 +56,7 @@ public class AndroidAptCompiler implements SourceGeneratingCompiler { private static final GenerationItem[] EMPTY_GENERATION_ITEM_ARRAY = {}; public static boolean isToCompileModule(Module module, AndroidFacetConfiguration configuration) { - if (configuration.ENABLE_AAPT_COMPILER && - !(configuration.COPY_RESOURCES_FROM_ARTIFACTS && AndroidMavenUtil.isMavenizedModule(module))) { + if (!(configuration.RUN_PROCESS_RESOURCES_MAVEN_TASK && AndroidMavenUtil.isMavenizedModule(module))) { return true; } return false; diff --git a/plugins/android/src/org/jetbrains/android/compiler/AndroidDexCompiler.java b/plugins/android/src/org/jetbrains/android/compiler/AndroidDexCompiler.java index f3f34929ea20..8b27e014e952 100644 --- a/plugins/android/src/org/jetbrains/android/compiler/AndroidDexCompiler.java +++ b/plugins/android/src/org/jetbrains/android/compiler/AndroidDexCompiler.java @@ -36,6 +36,8 @@ import org.jetbrains.android.dom.manifest.Manifest; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.android.facet.AndroidFacetConfiguration; import org.jetbrains.android.facet.AndroidRootUtil; +import org.jetbrains.android.maven.AndroidMavenProvider; +import org.jetbrains.android.maven.AndroidMavenUtil; import org.jetbrains.android.sdk.AndroidPlatform; import org.jetbrains.android.util.AndroidUtils; import org.jetbrains.annotations.NotNull; @@ -108,6 +110,22 @@ public class AndroidDexCompiler implements ClassPostProcessingCompiler { return new MyValidityState(map); } + public static VirtualFile getOutputDirectoryForDex(@NotNull Module module) { + if (AndroidMavenUtil.isMavenizedModule(module)) { + AndroidMavenProvider mavenProvider = AndroidMavenUtil.getMavenProvider(); + if (mavenProvider != null) { + String buildDirPath = mavenProvider.getBuildDirectory(module); + if (buildDirPath != null) { + VirtualFile buildDir = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(buildDirPath)); + if (buildDir != null) { + return buildDir; + } + } + } + } + return CompilerModuleExtension.getInstance(module).getCompilerOutputPath(); + } + private static final class PrepareAction implements Computable { private final CompileContext myContext; @@ -142,6 +160,9 @@ public class AndroidDexCompiler implements ClassPostProcessingCompiler { if (target != null) { Set excludedFiles = new HashSet(); collectClassFilesInLibraryModules(facet, excludedFiles); + + outputDir = getOutputDirectoryForDex(module); + items.add(new DexItem(module, outputDir, target, files, excludedFiles)); } } diff --git a/plugins/android/src/org/jetbrains/android/compiler/AndroidMavenResourcesCompiler.java b/plugins/android/src/org/jetbrains/android/compiler/AndroidMavenResourcesCompiler.java index e5eb49cd9069..467bf341c0cd 100644 --- a/plugins/android/src/org/jetbrains/android/compiler/AndroidMavenResourcesCompiler.java +++ b/plugins/android/src/org/jetbrains/android/compiler/AndroidMavenResourcesCompiler.java @@ -28,7 +28,6 @@ import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.android.compiler.tools.AndroidMavenExecutor; import org.jetbrains.android.dom.manifest.Manifest; import org.jetbrains.android.facet.AndroidFacet; -import org.jetbrains.android.facet.AndroidRootUtil; import org.jetbrains.android.maven.AndroidMavenProvider; import org.jetbrains.android.maven.AndroidMavenUtil; import org.jetbrains.android.util.AndroidUtils; @@ -63,7 +62,7 @@ public class AndroidMavenResourcesCompiler implements SourceGeneratingCompiler { public GenerationItem[] generate(final CompileContext context, final GenerationItem[] items, VirtualFile outputRootDirectory) { if (items != null && items.length > 0) { - context.getProgressIndicator().setText("Copying resources from Maven artifacts..."); + context.getProgressIndicator().setText("Processing resources by Maven..."); Computable computation = new Computable() { public GenerationItem[] compute() { if (context.getProject().isDisposed()) { @@ -175,11 +174,6 @@ public class AndroidMavenResourcesCompiler implements SourceGeneratingCompiler { } } - @Override - protected VirtualFile getResourcesDir(Module module, AndroidFacet facet) { - return AndroidRootUtil.getResourceDir(module); - } - public MyValidityState(DataInput is) throws IOException { super(is); int c = is.readInt(); @@ -227,7 +221,7 @@ public class AndroidMavenResourcesCompiler implements SourceGeneratingCompiler { MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(myContext.getProject()); if (mavenProjectsManager != null && mavenProjectsManager.isMavenizedModule(module)) { AndroidFacet facet = AndroidFacet.getInstance(module); - if (facet != null && facet.getConfiguration().COPY_RESOURCES_FROM_ARTIFACTS) { + if (facet != null && facet.getConfiguration().RUN_PROCESS_RESOURCES_MAVEN_TASK) { Manifest manifest = facet.getManifest(); String aPackage = manifest != null ? manifest.getPackage().getValue() : null; if (aPackage != null) { diff --git a/plugins/android/src/org/jetbrains/android/compiler/AndroidPackagingCompiler.java b/plugins/android/src/org/jetbrains/android/compiler/AndroidPackagingCompiler.java index 64011b818627..0e180b6ab206 100644 --- a/plugins/android/src/org/jetbrains/android/compiler/AndroidPackagingCompiler.java +++ b/plugins/android/src/org/jetbrains/android/compiler/AndroidPackagingCompiler.java @@ -63,8 +63,13 @@ public class AndroidPackagingCompiler implements PackagingCompiler { private static void fillSourceRoots(@NotNull Module module, @NotNull Set visited, @NotNull Set result) { visited.add(module); + VirtualFile resDir = AndroidRootUtil.getResourceDir(module); ModuleRootManager manager = ModuleRootManager.getInstance(module); - Collections.addAll(result, manager.getSourceRoots()); + for (VirtualFile sourceRoot : manager.getSourceRoots()) { + if (resDir != sourceRoot) { + result.add(sourceRoot); + } + } for (OrderEntry entry : manager.getOrderEntries()) { if (entry instanceof ModuleOrderEntry) { ModuleOrderEntry moduleOrderEntry = (ModuleOrderEntry)entry; @@ -97,17 +102,32 @@ public class AndroidPackagingCompiler implements PackagingCompiler { VirtualFile[] sourceRoots = getSourceRootsForModuleAndDependencies(module); if (manifestFile != null) { AndroidFacetConfiguration configuration = facet.getConfiguration(); - VirtualFile outputDir = context.getModuleOutputDirectory(module); + VirtualFile outputDir = AndroidDexCompiler.getOutputDirectoryForDex(module); if (outputDir != null) { VirtualFile[] externalJars = getExternalJars(module, configuration); - String resPackage = AndroidResourcesPackagingCompiler.getOutputPath(module, outputDir); - String outputPath = facet.getApkPath(); - String classesDexPath = new File(outputDir.getPath(), AndroidUtils.CLASSES_FILE_NAME).getPath(); + + File resPackage = AndroidResourcesPackagingCompiler.getOutputFile(module, outputDir); + String resPackagePath = FileUtil.toSystemDependentName(resPackage.getPath()); + if (!resPackage.exists()) { + context.addMessage(CompilerMessageCategory.ERROR, "File " + resPackagePath + " not found. Try to rebuild project", + null, -1, -1); + continue; + } + + File classesDexFile = new File(outputDir.getPath(), AndroidUtils.CLASSES_FILE_NAME); + String classesDexPath = FileUtil.toSystemDependentName(classesDexFile.getPath()); + if (!classesDexFile.exists()) { + context.addMessage(CompilerMessageCategory.ERROR, "File " + classesDexPath + " not found. Try to rebuild project", + null, -1, -1); + continue; + } + IAndroidTarget target = configuration.getAndroidTarget(); String sdkPath = configuration.getSdkPath(); + String outputPath = facet.getApkPath(); if (target != null && sdkPath != null && outputPath != null) { AptPackagingItem item = - new AptPackagingItem(sdkPath, manifestFile, resPackage, outputPath, configuration.GENERATE_UNSIGNED_APK); + new AptPackagingItem(sdkPath, manifestFile, resPackagePath, outputPath, configuration.GENERATE_UNSIGNED_APK); item.setNativeLibsFolders(collectNativeLibsFolders(facet)); item.setClassesDexPath(classesDexPath); item.setSourceRoots(sourceRoots); @@ -305,7 +325,7 @@ public class AndroidPackagingCompiler implements PackagingCompiler { VirtualFile[] sourceRoots, VirtualFile[] externalLibs, VirtualFile[] nativeLibFolders) { - myResourceTimestamps.put(manifestFile.getPath(), manifestFile.getTimeStamp()); + //myResourceTimestamps.put(manifestFile.getPath(), manifestFile.getTimeStamp()); myResourceTimestamps.put(FileUtil.toSystemIndependentName(resPackagePath), new File(resPackagePath).lastModified()); myResourceTimestamps.put(FileUtil.toSystemIndependentName(classesDexPath), new File(classesDexPath).lastModified()); myApkPath = apkPath; diff --git a/plugins/android/src/org/jetbrains/android/compiler/AndroidResourcesPackagingCompiler.java b/plugins/android/src/org/jetbrains/android/compiler/AndroidResourcesPackagingCompiler.java index 699cc023ff29..4d0fcc4fcec4 100644 --- a/plugins/android/src/org/jetbrains/android/compiler/AndroidResourcesPackagingCompiler.java +++ b/plugins/android/src/org/jetbrains/android/compiler/AndroidResourcesPackagingCompiler.java @@ -47,17 +47,24 @@ public class AndroidResourcesPackagingCompiler implements ClassPostProcessingCom if (facet != null && !facet.getConfiguration().LIBRARY_PROJECT) { VirtualFile manifestFile = AndroidRootUtil.getManifestFileForCompiler(facet); VirtualFile assetsDir = AndroidRootUtil.getAssetsDir(module); - if (manifestFile != null) { - AndroidFacetConfiguration configuration = facet.getConfiguration(); - VirtualFile outputDir = context.getModuleOutputDirectory(module); - if (outputDir != null) { - String outputPath = getOutputPath(module, outputDir); - IAndroidTarget target = configuration.getAndroidTarget(); - if (target != null) { - String assetsDirPath = assetsDir != null ? assetsDir.getPath() : null; - String[] resourcesDirPaths = AndroidCompileUtil.collectResourceDirs(facet); - items.add(new MyItem(module, target, manifestFile, resourcesDirPaths, assetsDirPath, outputPath)); + if (manifestFile == null) { + context.addMessage(CompilerMessageCategory.ERROR, "AndroidManifest.xml file not found. Please, check Android facet settings.", + null, -1, -1); + continue; + } + AndroidFacetConfiguration configuration = facet.getConfiguration(); + VirtualFile outputDir = AndroidDexCompiler.getOutputDirectoryForDex(module); + if (outputDir != null) { + String outputPath = getOutputFile(module, outputDir).getPath(); + IAndroidTarget target = configuration.getAndroidTarget(); + if (target != null) { + String assetsDirPath = assetsDir != null ? assetsDir.getPath() : null; + String[] resourcesDirPaths = AndroidCompileUtil.collectResourceDirs(facet); + if (resourcesDirPaths.length == 0) { + context.addMessage(CompilerMessageCategory.WARNING, "Resource directory not found for module " + module.getName(), + null, -1, -1); } + items.add(new MyItem(module, target, manifestFile, resourcesDirPaths, assetsDirPath, outputPath)); } } } @@ -65,8 +72,8 @@ public class AndroidResourcesPackagingCompiler implements ClassPostProcessingCom return items.toArray(new ProcessingItem[items.size()]); } - static String getOutputPath(Module module, VirtualFile outputDir) { - return new File(outputDir.getPath(), module.getName() + ".apk.res").getPath(); + static File getOutputFile(Module module, VirtualFile outputDir) { + return new File(outputDir.getPath(), module.getName() + ".apk.res"); } @Override @@ -138,7 +145,8 @@ public class AndroidResourcesPackagingCompiler implements ClassPostProcessingCom @NotNull @Override public VirtualFile getFile() { - return myManifestFile; + VirtualFile moduleFile = myModule.getModuleFile(); + return moduleFile != null ? moduleFile : myManifestFile; } @Override diff --git a/plugins/android/src/org/jetbrains/android/compiler/ResourcesValidityState.java b/plugins/android/src/org/jetbrains/android/compiler/ResourcesValidityState.java index 93a0d69ee056..4aa5018fbf59 100644 --- a/plugins/android/src/org/jetbrains/android/compiler/ResourcesValidityState.java +++ b/plugins/android/src/org/jetbrains/android/compiler/ResourcesValidityState.java @@ -49,7 +49,7 @@ public class ResourcesValidityState implements ValidityState { IAndroidTarget target = platform != null ? platform.getTarget() : null; myAndroidTargetName = target != null ? target.getFullName() : ""; - VirtualFile manifestFile = AndroidRootUtil.getManifestFileForCompiler(facet); + VirtualFile manifestFile = AndroidRootUtil.getManifestFile(module); if (manifestFile != null) { myResourceTimestamps.put(manifestFile.getPath(), manifestFile.getTimeStamp()); } @@ -58,7 +58,7 @@ public class ResourcesValidityState implements ValidityState { collectFiles(resourcesDir); } for (AndroidFacet depFacet : AndroidUtils.getAllAndroidDependencies(module, true)) { - VirtualFile depManifest = AndroidRootUtil.getManifestFileForCompiler(depFacet); + VirtualFile depManifest = AndroidRootUtil.getManifestFile(depFacet.getModule()); if (depManifest != null) { myResourceTimestamps.put(depManifest.getPath(), depManifest.getTimeStamp()); } @@ -74,8 +74,15 @@ public class ResourcesValidityState implements ValidityState { } @Nullable - protected VirtualFile getResourcesDir(Module module, AndroidFacet facet) { - return AndroidAptCompiler.getResourceDirForApkCompiler(module, facet); + private static VirtualFile getResourcesDir(Module module, AndroidFacet facet) { + VirtualFile dir = AndroidAptCompiler.getResourceDirForApkCompiler(module, facet); + if (dir != null) { + VirtualFile parent = dir.getParent(); + if ("combined-resources".equals(parent.getName())) { + return dir; + } + } + return AndroidRootUtil.getResourceDir(module); } private void collectFiles(VirtualFile resourcesDir) { diff --git a/plugins/android/src/org/jetbrains/android/compiler/tools/AndroidMavenExecutor.java b/plugins/android/src/org/jetbrains/android/compiler/tools/AndroidMavenExecutor.java index edb721cd88b9..df9b958379fe 100644 --- a/plugins/android/src/org/jetbrains/android/compiler/tools/AndroidMavenExecutor.java +++ b/plugins/android/src/org/jetbrains/android/compiler/tools/AndroidMavenExecutor.java @@ -54,7 +54,7 @@ public class AndroidMavenExecutor { MavenRunnerParameters parameters = new MavenRunnerParameters(true, projectsManager.findProject(module).getDirectory(), - Collections.singletonList("generate-resources"), + Collections.singletonList("process-resources"), projectsManager.getExplicitProfiles()); Map> result = new HashMap>(); diff --git a/plugins/android/src/org/jetbrains/android/dom/AndroidDomExtender.java b/plugins/android/src/org/jetbrains/android/dom/AndroidDomExtender.java index a1aaeff76e9a..8c034deedff3 100644 --- a/plugins/android/src/org/jetbrains/android/dom/AndroidDomExtender.java +++ b/plugins/android/src/org/jetbrains/android/dom/AndroidDomExtender.java @@ -357,10 +357,15 @@ public class AndroidDomExtender extends DomExtender { public void process(@NotNull XmlName attrName, @NotNull DomExtension extension, @NotNull DomElement element) { if (element instanceof LayoutViewElement && SdkConstants.NS_RESOURCES.equals(attrName.getNamespaceKey())) { XmlElement xmlElement = element.getXmlElement(); - String tagName = xmlElement instanceof XmlTag ? ((XmlTag)xmlElement).getName() : null; - if (!"merge".equals(tagName) && - ("layout_width".equals(attrName.getLocalName()) || "layout_height".equals(attrName.getLocalName()))) { - extension.addCustomAnnotation(new MyRequired()); + XmlTag tag = xmlElement instanceof XmlTag ? (XmlTag)xmlElement : null; + String tagName = tag != null ? tag.getName() : null; + if (!"merge".equals(tagName) && (tag == null || tag.getAttribute("style") == null)) { + XmlTag parentTag = tag != null ? tag.getParentTag() : null; + String parentTagName = parentTag != null ? parentTag.getName() : null; + if (!"TableRow".equals(parentTagName) && !"TableLayout".equals(parentTagName) && + ("layout_width".equals(attrName.getLocalName()) || "layout_height".equals(attrName.getLocalName()))) { + extension.addCustomAnnotation(new MyRequired()); + } } } } diff --git a/plugins/android/src/org/jetbrains/android/dom/converters/BaseResourceReference.java b/plugins/android/src/org/jetbrains/android/dom/converters/BaseResourceReference.java index 6dd847894489..b4506568847e 100644 --- a/plugins/android/src/org/jetbrains/android/dom/converters/BaseResourceReference.java +++ b/plugins/android/src/org/jetbrains/android/dom/converters/BaseResourceReference.java @@ -77,4 +77,9 @@ public abstract class BaseResourceReference extends PsiReferenceBase.Poly { private boolean canRunOnDevice(IAndroidTarget projectTarget, AndroidVersion deviceVersion) { int minSdkVersion = -1; int maxSdkVersion = -1; - Manifest manifest = getManifest(); + final Manifest manifest = getManifest(); if (manifest != null) { - XmlTag manifestTag = manifest.getXmlTag(); + XmlTag manifestTag = ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + public XmlTag compute() { + return manifest.getXmlTag(); + } + }); if (manifestTag != null) { XmlTag[] tags = manifestTag.findSubTags("uses-sdk"); for (XmlTag tag : tags) { diff --git a/plugins/android/src/org/jetbrains/android/facet/AndroidFacetConfiguration.java b/plugins/android/src/org/jetbrains/android/facet/AndroidFacetConfiguration.java index 9cc8d2e7309f..d62310352af6 100644 --- a/plugins/android/src/org/jetbrains/android/facet/AndroidFacetConfiguration.java +++ b/plugins/android/src/org/jetbrains/android/facet/AndroidFacetConfiguration.java @@ -66,9 +66,7 @@ public class AndroidFacetConfiguration implements FacetConfiguration { public boolean LIBRARY_PROJECT = false; - public boolean COPY_RESOURCES_FROM_ARTIFACTS = true; - - public boolean ENABLE_AAPT_COMPILER = true; + public boolean RUN_PROCESS_RESOURCES_MAVEN_TASK = true; public boolean GENERATE_UNSIGNED_APK = false; diff --git a/plugins/android/src/org/jetbrains/android/facet/AndroidFacetEditorTab.form b/plugins/android/src/org/jetbrains/android/facet/AndroidFacetEditorTab.form index cc727652b412..a2be05723872 100644 --- a/plugins/android/src/org/jetbrains/android/facet/AndroidFacetEditorTab.form +++ b/plugins/android/src/org/jetbrains/android/facet/AndroidFacetEditorTab.form @@ -3,7 +3,7 @@ - + @@ -176,7 +176,7 @@ - + @@ -184,82 +184,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -312,47 +240,96 @@ - + - + + - + - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -379,5 +356,9 @@ + + + + diff --git a/plugins/android/src/org/jetbrains/android/facet/AndroidFacetEditorTab.java b/plugins/android/src/org/jetbrains/android/facet/AndroidFacetEditorTab.java index a2e8b416cae3..166f85ce7956 100644 --- a/plugins/android/src/org/jetbrains/android/facet/AndroidFacetEditorTab.java +++ b/plugins/android/src/org/jetbrains/android/facet/AndroidFacetEditorTab.java @@ -93,8 +93,6 @@ public class AndroidFacetEditorTab extends FacetEditorTab { private JCheckBox myGenerateRJavaWhenChanged; private JCheckBox myGenerateIdlWhenChanged; private JCheckBox myIsLibraryProjectCheckbox; - private JCheckBox myCopyResourcesFromArtifacts; - private JCheckBox myEnableAaptCompiler; private JPanel myAaptCompilerPanel; private JBList myResOverlayList; private JButton myAddResOverlayButton; @@ -103,9 +101,8 @@ public class AndroidFacetEditorTab extends FacetEditorTab { private JCheckBox myGenerateUnsignedApk; private ComboboxWithBrowseButton myApkPathCombo; private JLabel myApkPathLabel; - private JRadioButton myUseCompilerManifestFromStructureRadio; - private JRadioButton myUseCustomCompilerManifestRadio; - private TextFieldWithBrowseButton myCustomCompilerManifestPathField; + private JRadioButton myRunProcessResourcesRadio; + private JRadioButton myCompileResourcesByIdeRadio; public AndroidFacetEditorTab(FacetEditorContext context, AndroidFacetConfiguration androidFacetConfiguration) { final Project project = context.getProject(); @@ -133,9 +130,6 @@ public class AndroidFacetEditorTab extends FacetEditorTab { myCustomAptSourceDirField.getButton().addActionListener(new MyFolderFieldListener(myCustomAptSourceDirField, AndroidAptCompiler.getCustomResourceDirForApt(facet), false)); - myCustomCompilerManifestPathField.getButton().addActionListener(new MyFolderFieldListener(myCustomCompilerManifestPathField, - AndroidRootUtil.getManifestFileForCompiler(facet), - true)); myPlatformChooser.addListener(new AndroidPlatformChooserListener() { @Override @@ -182,15 +176,6 @@ public class AndroidFacetEditorTab extends FacetEditorTab { myUseCustomSourceDirectoryRadio.addActionListener(listener); myUseAptResDirectoryFromPathRadio.addActionListener(listener); - listener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - myCustomCompilerManifestPathField.setEnabled(myUseCustomCompilerManifestRadio.isSelected()); - } - }; - myUseCustomCompilerManifestRadio.addActionListener(listener); - myUseCompilerManifestFromStructureRadio.addActionListener(listener); - myIsLibraryProjectCheckbox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { @@ -204,15 +189,11 @@ public class AndroidFacetEditorTab extends FacetEditorTab { listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - UIUtil.setEnabled(myAaptCompilerPanel, myEnableAaptCompiler.isSelected(), true); - myEnableAaptCompiler.setEnabled(true); - if (myCopyResourcesFromArtifacts.isVisible() && myCopyResourcesFromArtifacts.isSelected()) { - UIUtil.setEnabled(myAaptCompilerPanel, false, true); - } + updateAptPanel(); } }; - myEnableAaptCompiler.addActionListener(listener); - myCopyResourcesFromArtifacts.addActionListener(listener); + myRunProcessResourcesRadio.addActionListener(listener); + myCompileResourcesByIdeRadio.addActionListener(listener); myAddResOverlayButton.addActionListener(new ActionListener() { @Override @@ -263,6 +244,11 @@ public class AndroidFacetEditorTab extends FacetEditorTab { }); } + private void updateAptPanel() { + boolean enabled = !myRunProcessResourcesRadio.isVisible() || !myRunProcessResourcesRadio.isSelected(); + UIUtil.setEnabled(myAaptCompilerPanel, enabled, true); + } + private static String[] getDefaultApks(@NotNull Module module) { List result = new ArrayList(); String path = AndroidFacet.getOutputPackage(module); @@ -348,24 +334,13 @@ public class AndroidFacetEditorTab extends FacetEditorTab { return true; } - if (myUseCustomCompilerManifestRadio.isSelected() != myConfiguration.USE_CUSTOM_COMPILER_MANIFEST) { - return true; - } - if (checkRelativePath(myConfiguration.CUSTOM_COMPILER_MANIFEST, myCustomCompilerManifestPathField.getText())) { - return true; - } - - if (myCopyResourcesFromArtifacts.isSelected() != myConfiguration.COPY_RESOURCES_FROM_ARTIFACTS) { + if (myRunProcessResourcesRadio.isSelected() != myConfiguration.RUN_PROCESS_RESOURCES_MAVEN_TASK) { return true; } if (myGenerateUnsignedApk.isSelected() != myConfiguration.GENERATE_UNSIGNED_APK) { return true; } - if (myEnableAaptCompiler.isSelected() != myConfiguration.ENABLE_AAPT_COMPILER) { - return true; - } - List currentResOverlayFolders = new ArrayList(); for (String folder : myConfiguration.RES_OVERLAY_FOLDERS) { String absPath = toAbsolutePath(folder); @@ -498,7 +473,7 @@ public class AndroidFacetEditorTab extends FacetEditorTab { myConfiguration.LIBRARY_PROJECT = myIsLibraryProjectCheckbox.isSelected(); - myConfiguration.COPY_RESOURCES_FROM_ARTIFACTS = myCopyResourcesFromArtifacts.isSelected(); + myConfiguration.RUN_PROCESS_RESOURCES_MAVEN_TASK = myRunProcessResourcesRadio.isSelected(); myConfiguration.GENERATE_UNSIGNED_APK = myGenerateUnsignedApk.isSelected(); @@ -517,22 +492,11 @@ public class AndroidFacetEditorTab extends FacetEditorTab { } myConfiguration.USE_CUSTOM_APK_RESOURCE_FOLDER = useCustomAptSrc; - boolean useCustomCompilerManifest = myUseCustomCompilerManifestRadio.isSelected(); - if (myConfiguration.USE_CUSTOM_COMPILER_MANIFEST != useCustomCompilerManifest) { - runApt = true; - } - myConfiguration.USE_CUSTOM_COMPILER_MANIFEST = useCustomCompilerManifest; - if (myConfiguration.REGENERATE_R_JAVA != myGenerateRJavaWhenChanged.isSelected()) { runApt = true; } myConfiguration.REGENERATE_R_JAVA = myGenerateRJavaWhenChanged.isSelected(); - if (myConfiguration.ENABLE_AAPT_COMPILER != myEnableAaptCompiler.isSelected()) { - runApt = true; - } - myConfiguration.ENABLE_AAPT_COMPILER = myEnableAaptCompiler.isSelected(); - if (myConfiguration.REGENERATE_JAVA_BY_AIDL != myGenerateIdlWhenChanged.isSelected()) { runIdl = true; } @@ -554,25 +518,6 @@ public class AndroidFacetEditorTab extends FacetEditorTab { myConfiguration.CUSTOM_APK_RESOURCE_FOLDER = relPath != null ? '/' + relPath : ""; } - String absCompilerManifestPath = myCustomCompilerManifestPathField.getText().trim(); - if (useCustomCompilerManifest) { - if (absCompilerManifestPath.length() == 0) { - throw new ConfigurationException("AndroidManifest.xml path not specified in \"Compiler\" section"); - } - String newCustomCompilerManifestPath = '/' + getAndCheckRelativePath(absCompilerManifestPath, false); - if (!SdkConstants.FN_ANDROID_MANIFEST_XML.equals(AndroidUtils.getSimpleNameByRelativePath(newCustomCompilerManifestPath))) { - throw new ConfigurationException("Manifest file must have name AndroidManifest.xml"); - } - if (!newCustomCompilerManifestPath.equals(myConfiguration.CUSTOM_COMPILER_MANIFEST)) { - runApt = true; - } - myConfiguration.CUSTOM_COMPILER_MANIFEST = newCustomCompilerManifestPath; - } - else { - String relPath = toRelativePath(absCompilerManifestPath); - myConfiguration.CUSTOM_COMPILER_MANIFEST = relPath != null ? '/' + relPath : ""; - } - final AndroidPlatform platform = myPlatformChooser.getSelectedPlatform(); myConfiguration.setAndroidPlatform(platform); final AndroidFacet facet = myConfiguration.getFacet(); @@ -704,21 +649,15 @@ public class AndroidFacetEditorTab extends FacetEditorTab { myCustomAptSourceDirField.setText(aptSourceAbsPath != null ? aptSourceAbsPath : ""); myCustomAptSourceDirField.setEnabled(configuration.USE_CUSTOM_APK_RESOURCE_FOLDER); - myUseCustomCompilerManifestRadio.setSelected(configuration.USE_CUSTOM_COMPILER_MANIFEST); - myUseCompilerManifestFromStructureRadio.setSelected(!configuration.USE_CUSTOM_COMPILER_MANIFEST); - - String compilerManifestPath = configuration.CUSTOM_COMPILER_MANIFEST; - String compilerManifestAbsPath = compilerManifestPath.length() > 0 ? toAbsolutePath(compilerManifestPath) : ""; - myCustomCompilerManifestPathField.setText(compilerManifestAbsPath != null ? compilerManifestAbsPath : ""); - myCustomCompilerManifestPathField.setEnabled(configuration.USE_CUSTOM_COMPILER_MANIFEST); - String apkPath = configuration.APK_PATH; String apkAbsPath = apkPath.length() > 0 ? toAbsolutePath(apkPath) : ""; myApkPathCombo.getComboBox().getEditor().setItem(apkAbsPath != null ? apkAbsPath : ""); boolean mavenizedModule = AndroidMavenUtil.isMavenizedModule(myContext.getModule()); - myCopyResourcesFromArtifacts.setVisible(mavenizedModule); - myCopyResourcesFromArtifacts.setSelected(myConfiguration.COPY_RESOURCES_FROM_ARTIFACTS); + myRunProcessResourcesRadio.setVisible(mavenizedModule); + myRunProcessResourcesRadio.setSelected(myConfiguration.RUN_PROCESS_RESOURCES_MAVEN_TASK); + myCompileResourcesByIdeRadio.setVisible(mavenizedModule); + myCompileResourcesByIdeRadio.setSelected(!myConfiguration.RUN_PROCESS_RESOURCES_MAVEN_TASK); myGenerateUnsignedApk.setSelected(myConfiguration.GENERATE_UNSIGNED_APK); @@ -737,12 +676,7 @@ public class AndroidFacetEditorTab extends FacetEditorTab { } myResOverlayList.setModel(new CollectionListModel(items)); - myEnableAaptCompiler.setSelected(myConfiguration.ENABLE_AAPT_COMPILER); - UIUtil.setEnabled(myAaptCompilerPanel, myEnableAaptCompiler.isSelected(), true); - myEnableAaptCompiler.setEnabled(true); - if (myCopyResourcesFromArtifacts.isSelected() && myCopyResourcesFromArtifacts.isVisible()) { - UIUtil.setEnabled(myAaptCompilerPanel, false, true); - } + updateAptPanel(); } @Nullable diff --git a/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatToolWindowFactory.java b/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatToolWindowFactory.java index dcb4c0ff0154..4300826cd24a 100644 --- a/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatToolWindowFactory.java +++ b/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatToolWindowFactory.java @@ -16,9 +16,12 @@ package org.jetbrains.android.logcat; +import com.intellij.CommonBundle; +import com.intellij.facet.ProjectFacetManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Condition; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowFactory; @@ -28,10 +31,12 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import org.jetbrains.android.facet.AndroidFacet; +import org.jetbrains.android.sdk.AndroidPlatform; import org.jetbrains.android.util.AndroidBundle; import org.jetbrains.android.util.AndroidUtils; import javax.swing.*; +import java.util.List; /** * @author Eugene.Kudelevsky @@ -44,6 +49,19 @@ public class AndroidLogcatToolWindowFactory implements ToolWindowFactory, Condit toolWindow.setAvailable(true, null); toolWindow.setToHideOnEmptyContent(true); toolWindow.setTitle(TOOL_WINDOW_ID); + + List facets = ProjectFacetManager.getInstance(project).getFacets(AndroidFacet.ID); + if (facets.size() == 0) { + Messages.showErrorDialog(project, AndroidBundle.message("android.logcat.no.android.facets.error"), CommonBundle.getErrorTitle()); + return; + } + AndroidFacet facet = facets.get(0); + AndroidPlatform platform = facet.getConfiguration().getAndroidPlatform(); + if (platform == null) { + Messages.showErrorDialog(project, AndroidBundle.message("specify.platform.error"), CommonBundle.getErrorTitle()); + return; + } + final AndroidLogcatToolWindowView view = new AndroidLogcatToolWindowView(project) { @Override protected boolean isActive() { diff --git a/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatToolWindowView.java b/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatToolWindowView.java index 11e4ab671443..54090012c0ed 100644 --- a/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatToolWindowView.java +++ b/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatToolWindowView.java @@ -36,8 +36,6 @@ import org.jetbrains.android.actions.AndroidEnableDdmsAction; import org.jetbrains.android.ddms.AdbManager; import org.jetbrains.android.ddms.AdbNotRespondingException; import org.jetbrains.android.facet.AndroidFacet; -import org.jetbrains.android.sdk.AndroidPlatform; -import org.jetbrains.android.util.AndroidBundle; import org.jetbrains.android.util.AndroidUtils; import org.jetbrains.annotations.NotNull; @@ -63,7 +61,7 @@ public abstract class AndroidLogcatToolWindowView implements Disposable { private JPanel mySearchComponentWrapper; private volatile IDevice myDevice; private final Object myLock = new Object(); - private volatile LogConsoleBase myLogConsole; + private final LogConsoleBase myLogConsole; private volatile Reader myCurrentReader; private final AndroidDebugBridge.IDeviceChangeListener myDeviceChangeListener = new AndroidDebugBridge.IDeviceChangeListener() { @@ -110,18 +108,6 @@ public abstract class AndroidLogcatToolWindowView implements Disposable { myProject = project; Disposer.register(myProject, this); - List facets = ProjectFacetManager.getInstance(project).getFacets(AndroidFacet.ID); - if (facets.size() == 0) { - Messages.showErrorDialog(project, AndroidBundle.message("android.logcat.no.android.facets.error"), CommonBundle.getErrorTitle()); - return; - } - AndroidFacet facet = facets.get(0); - AndroidPlatform platform = facet.getConfiguration().getAndroidPlatform(); - if (platform == null) { - Messages.showErrorDialog(project, AndroidBundle.message("specify.platform.error"), CommonBundle.getErrorTitle()); - return; - } - myDeviceCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateLogConsole(); diff --git a/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatUtil.java b/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatUtil.java index fc3863cd5f1e..c6b5bbeb173a 100644 --- a/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatUtil.java +++ b/plugins/android/src/org/jetbrains/android/logcat/AndroidLogcatUtil.java @@ -29,6 +29,7 @@ import org.jetbrains.android.run.LoggingReceiver; import org.jetbrains.android.util.AndroidBundle; import org.jetbrains.android.util.AndroidOutputReceiver; import org.jetbrains.android.util.AndroidUtils; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; @@ -100,7 +101,7 @@ public class AndroidLogcatUtil { public static Reader startLoggingThread(final Project project, final IDevice device, final boolean clearLogcat, - final LogConsoleBase console) { + @NotNull final LogConsoleBase console) { UIUtil.invokeAndWaitIfNeeded(new Runnable() { public void run() { console.clear(); diff --git a/plugins/android/src/org/jetbrains/android/maven/AndroidFacetImporter.java b/plugins/android/src/org/jetbrains/android/maven/AndroidFacetImporter.java index 5b41168a1c68..00079881b991 100644 --- a/plugins/android/src/org/jetbrains/android/maven/AndroidFacetImporter.java +++ b/plugins/android/src/org/jetbrains/android/maven/AndroidFacetImporter.java @@ -174,13 +174,14 @@ public class AndroidFacetImporter extends FacetImporter + + +