diff --git a/.idea/libraries/Guava.xml b/.idea/libraries/Guava.xml index 555ca8377a3c..649397a32e38 100644 --- a/.idea/libraries/Guava.xml +++ b/.idea/libraries/Guava.xml @@ -1,11 +1,11 @@ - + - + \ No newline at end of file diff --git a/build/scripts/layouts.gant b/build/scripts/layouts.gant index 60bece10bfc9..923a39ebf639 100644 --- a/build/scripts/layouts.gant +++ b/build/scripts/layouts.gant @@ -505,7 +505,7 @@ def layout_core(String home, String target) { } fileset(dir: "$home/lib") { - include(name: "guava-11.0.1.jar") + include(name: "guava-12.0.jar") include(name: "picocontainer.jar") include(name: "trove4j.jar") include(name: "asm.jar") @@ -537,7 +537,7 @@ def layout_core_upsource(String home, String target) { } fileset(dir: "$home/lib") { - include(name: "guava-11.0.1.jar") + include(name: "guava-12.0.jar") include(name: "picocontainer.jar") include(name: "trove4j.jar") include(name: "asm.jar") diff --git a/java/compiler/forms-compiler/src/com/intellij/uiDesigner/compiler/AsmCodeGenerator.java b/java/compiler/forms-compiler/src/com/intellij/uiDesigner/compiler/AsmCodeGenerator.java index e3c299a55d79..004209e3930c 100644 --- a/java/compiler/forms-compiler/src/com/intellij/uiDesigner/compiler/AsmCodeGenerator.java +++ b/java/compiler/forms-compiler/src/com/intellij/uiDesigner/compiler/AsmCodeGenerator.java @@ -858,7 +858,7 @@ public class AsmCodeGenerator { pushBorderProperties(container, generator, borderTitle, componentLocal); if (Boolean.valueOf(System.getProperty("idea.is.internal")).booleanValue()) { - container.getDelegeeClientProperties().put(ourBorderFactoryClientProperty, "com.intellij.ui.IdeBorderFactory$PlainSmallWithIndent"); + container.getDelegeeClientProperties().put(ourBorderFactoryClientProperty, StringDescriptor.create("com.intellij.ui.IdeBorderFactory$PlainSmallWithIndent")); } Type borderFactoryType = ourBorderFactoryType; diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java index 5a0ba7439fb2..5b88d0b428ea 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java @@ -19,12 +19,12 @@ import com.intellij.ProjectTopics; import com.intellij.application.options.PathMacrosImpl; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.compiler.server.impl.CompileServerClasspathManager; +import com.intellij.execution.ExecutionAdapter; import com.intellij.execution.ExecutionException; +import com.intellij.execution.ExecutionManager; import com.intellij.execution.configurations.GeneralCommandLine; -import com.intellij.execution.process.OSProcessHandler; -import com.intellij.execution.process.ProcessAdapter; -import com.intellij.execution.process.ProcessEvent; -import com.intellij.execution.process.ProcessOutputTypes; +import com.intellij.execution.configurations.RunProfile; +import com.intellij.execution.process.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathMacros; import com.intellij.openapi.application.PathManager; @@ -114,9 +114,11 @@ public class BuildManager implements ApplicationComponent{ } }; private final SequentialTaskExecutor myEventsProcessor = new SequentialTaskExecutor(myPooledThreadExecutor); - private final Map myProjectDataMap = Collections.synchronizedMap(new HashMap()); + private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD); + private final AtomicBoolean myAutoMakeInProgress = new AtomicBoolean(false); + private final ChannelGroup myAllOpenChannels = new DefaultChannelGroup("build-manager"); private final BuildMessageDispatcher myMessageDispatcher = new BuildMessageDispatcher(); private int myListenPort = -1; @@ -137,8 +139,6 @@ public class BuildManager implements ApplicationComponent{ projectManager.addProjectManagerListener(new ProjectWatcher()); final MessageBusConnection conn = ApplicationManager.getApplication().getMessageBus().connect(); conn.subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() { - private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD); - private final AtomicBoolean myAutoMakeInProgress = new AtomicBoolean(false); @Override public void before(@NotNull List events) { } @@ -146,44 +146,11 @@ public class BuildManager implements ApplicationComponent{ @Override public void after(@NotNull List events) { if (shouldTriggerMake(events)) { - scheduleMake(new Runnable() { - @Override - public void run() { - if (!myAutoMakeInProgress.getAndSet(true)) { - try { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - runAutoMake(); - } - finally { - myAutoMakeInProgress.set(false); - } - } - }); - } - catch (RejectedExecutionException ignored) { - // we were shut down - } - } - else { - scheduleMake(this); - } - } - }); + scheduleAutoMake(); } } - private void scheduleMake(Runnable runnable) { - myAlarm.cancelAllRequests(); - myAlarm.addRequest(runnable, MAKE_TRIGGER_DELAY); - } - private boolean shouldTriggerMake(List events) { - if (!CompilerWorkspaceConfiguration.useServerlessOutOfProcessBuild()) { - return false; - } for (VFileEvent event : events) { if (event.isFromRefresh() || event.getRequestor() instanceof SavingRequestor) { return true; @@ -265,10 +232,46 @@ public class BuildManager implements ApplicationComponent{ return vFile != null ? vFile.getPath() : null; } - private void runAutoMake() { + private void scheduleAutoMake() { if (ApplicationManager.getApplication().isUnitTestMode()) { return; } + if (CompilerWorkspaceConfiguration.useServerlessOutOfProcessBuild()) { + addMakeRequest(new Runnable() { + @Override + public void run() { + if (!myAutoMakeInProgress.getAndSet(true)) { + try { + ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { + @Override + public void run() { + try { + runAutoMake(); + } + finally { + myAutoMakeInProgress.set(false); + } + } + }); + } + catch (RejectedExecutionException ignored) { + // we were shut down + } + } + else { + addMakeRequest(this); + } + } + }); + } + } + + private void addMakeRequest(Runnable runnable) { + myAlarm.cancelAllRequests(); + myAlarm.addRequest(runnable, MAKE_TRIGGER_DELAY); + } + + private void runAutoMake() { final Project[] openProjects = myProjectManager.getOpenProjects(); if (openProjects.length > 0) { final List futures = new ArrayList(); @@ -412,7 +415,7 @@ public class BuildManager implements ApplicationComponent{ public void onTextAvailable(ProcessEvent event, Key outputType) { // re-translate builder's output to idea.log final String text = event.getText(); - if (!StringUtil.isEmpty(text)) { + if (!StringUtil.isEmptyOrSpaces(text)) { LOG.info("BUILDER_PROCESS [" + outputType.toString() + "]: " + text.trim()); if (stdErrOutput.length() < 1024 && ProcessOutputTypes.STDERR.equals(outputType)) { stdErrOutput.append(text); @@ -819,6 +822,12 @@ public class BuildManager implements ApplicationComponent{ } } }); + conn.subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionAdapter() { + @Override + public void processTerminated(@NotNull RunProfile runProfile, @NotNull ProcessHandler handler) { + scheduleAutoMake(); + } + }); } @Override diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/JavaEditBreakpointActionHandler.java b/java/debugger/impl/src/com/intellij/debugger/actions/JavaEditBreakpointActionHandler.java index 1278f72e8c35..0a450e5454b8 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/JavaEditBreakpointActionHandler.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/JavaEditBreakpointActionHandler.java @@ -32,8 +32,10 @@ import com.intellij.openapi.ui.popup.LightweightWindowEvent; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.wm.IdeFocusManager; +import com.intellij.util.ui.UIUtil; import com.intellij.xdebugger.impl.actions.EditBreakpointActionHandler; import com.intellij.xdebugger.impl.breakpoints.XBreakpointUtil; +import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointsMasterDetailPopupFactory; import com.intellij.xdebugger.impl.ui.DebuggerUIUtil; import org.jetbrains.annotations.NotNull; @@ -49,7 +51,7 @@ import java.awt.*; */ public class JavaEditBreakpointActionHandler extends EditBreakpointActionHandler { @Override - protected void doShowPopup(Project project, final EditorGutterComponentEx gutterComponent, final Point whereToShow, Object breakpoint) { + protected void doShowPopup(final Project project, final EditorGutterComponentEx gutterComponent, final Point whereToShow, Object breakpoint) { if (!(breakpoint instanceof BreakpointWithHighlighter)) return; final BreakpointWithHighlighter javaBreakpoint = (BreakpointWithHighlighter)breakpoint; @@ -88,13 +90,16 @@ public class JavaEditBreakpointActionHandler extends EditBreakpointActionHandler final Runnable showMoreOptions = new Runnable() { @Override public void run() { - propertiesPanel.setMoreOptionsVisible(true); - final Balloon newBalloon = DebuggerUIUtil.showBreakpointEditor(mainPanel, displayName, whereToShow, gutterComponent, null); - newBalloon.addListener(saveOnClose); + UIUtil.invokeLaterIfNeeded(new Runnable() { + @Override + public void run() { + BreakpointsMasterDetailPopupFactory. + getInstance(project).createPopup(javaBreakpoint).showCenteredInCurrentWindow(project); + } + }); } }; - final Balloon balloon = DebuggerUIUtil.showBreakpointEditor(mainPanel, displayName, whereToShow, gutterComponent, - propertiesPanel.isMoreOptionsVisible() ? null : showMoreOptions); + final Balloon balloon = DebuggerUIUtil.showBreakpointEditor(project, mainPanel, displayName, whereToShow, gutterComponent, showMoreOptions); balloon.addListener(saveOnClose); propertiesPanel.setDelegate(new BreakpointPropertiesPanel.Delegate() { @@ -103,7 +108,7 @@ public class JavaEditBreakpointActionHandler extends EditBreakpointActionHandler propertiesPanel.setActionsPanelVisible(true); balloon.hide(); final Balloon newBalloon = - DebuggerUIUtil.showBreakpointEditor(mainPanel, displayName, whereToShow, gutterComponent, showMoreOptions); + DebuggerUIUtil.showBreakpointEditor(project, mainPanel, displayName, whereToShow, gutterComponent, showMoreOptions); newBalloon.addListener(saveOnClose); } }); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java index d920f3993df3..a596e30b5565 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ package com.intellij.debugger.engine.evaluation.expression; import com.intellij.codeInsight.daemon.JavaErrorMessages; +import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.SourcePosition; @@ -160,7 +161,7 @@ public class EvaluatorBuilderImpl implements EvaluatorBuilder { final PsiType unboxedLType = PsiPrimitiveType.getUnboxedType(lType); if (unboxedLType != null) { - if (rType instanceof PsiPrimitiveType && !PsiPrimitiveType.NULL.equals(rType)) { + if (rType instanceof PsiPrimitiveType && !PsiType.NULL.equals(rType)) { if (!rType.equals(unboxedLType)) { rEvaluator = new TypeCastEvaluator(rEvaluator, unboxedLType.getCanonicalText(), true); } @@ -175,7 +176,7 @@ public class EvaluatorBuilderImpl implements EvaluatorBuilder { } final PsiPrimitiveType unboxedRType = PsiPrimitiveType.getUnboxedType(rType); final PsiType _rType = unboxedRType != null? unboxedRType : rType; - if (_rType instanceof PsiPrimitiveType && !PsiPrimitiveType.NULL.equals(_rType)) { + if (_rType instanceof PsiPrimitiveType && !PsiType.NULL.equals(_rType)) { if (!lType.equals(_rType)) { rEvaluator = new TypeCastEvaluator(rEvaluator, lType.getCanonicalText(), true); } @@ -988,9 +989,9 @@ public class EvaluatorBuilderImpl implements EvaluatorBuilder { @Override public void visitLiteralExpression(PsiLiteralExpression expression) { - final String parsingError = HighlightUtil.getLiteralExpressionParsingError(expression); + final HighlightInfo parsingError = HighlightUtil.checkLiteralExpressionParsingError(expression); if (parsingError != null) { - throwEvaluateException(parsingError); + throwEvaluateException(parsingError.description); return; } @@ -1219,9 +1220,9 @@ public class EvaluatorBuilderImpl implements EvaluatorBuilder { myResult = new ArrayInitializerEvaluator(evaluators); } + @Nullable private static PsiClass getOuterClass(PsiClass aClass) { - if(aClass == null) return null; - return PsiTreeUtil.getContextOfType(aClass, PsiClass.class, true); + return aClass == null ? null : PsiTreeUtil.getContextOfType(aClass, PsiClass.class, true); } private PsiClass getContainingClass(PsiVariable variable) { diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java b/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java index 675ba7211a7a..2dda3d70feb4 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java @@ -214,8 +214,10 @@ public class JavaDebuggerSupport extends DebuggerSupport { } @Override - public void provideBreakpointsGroupingRules(Collection rules) { + public void createBreakpointsGroupingRules(Collection rules) { rules.add(new XBreakpointGroupingByCategoryRule()); + rules.add(new XBreakpointGroupingByPackageRule()); + rules.add(new XBreakpointGroupingByClassRule()); } @Override diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointClassGroup.java b/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointClassGroup.java new file mode 100644 index 000000000000..5a81258caaa4 --- /dev/null +++ b/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointClassGroup.java @@ -0,0 +1,58 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.debugger.ui; + +import com.intellij.debugger.DebuggerBundle; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.util.PlatformIcons; +import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroup; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; + +public class XBreakpointClassGroup extends XBreakpointGroup { + private static final String DEFAULT_PACKAGE_NAME = DebuggerBundle.message("default.package.name"); + + private String myPackageName; + private String myClassName; + + public XBreakpointClassGroup(@Nullable String packageName, String className) { + myPackageName = packageName != null ? packageName : DEFAULT_PACKAGE_NAME; + myClassName = className; + } + + @Override + public Icon getIcon(boolean isOpen) { + return PlatformIcons.CLASS_ICON; + } + + @NotNull + @Override + public String getName() { + return getClassName(); + } + + @NotNull + public String getPackageName() { + return myPackageName; + } + + @NotNull + public String getClassName() { + return myClassName; + } +} diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointGroupingByCategoryRule.java b/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointGroupingByCategoryRule.java index 477417f54ee7..7b8fe5d4b767 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointGroupingByCategoryRule.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointGroupingByCategoryRule.java @@ -22,18 +22,16 @@ import org.jetbrains.annotations.NotNull; import java.util.Collection; -/** -* Created with IntelliJ IDEA. -* User: zajac -* Date: 23.05.12 -* Time: 16:24 -* To change this template use File | Settings | File Templates. -*/ class XBreakpointGroupingByCategoryRule extends XBreakpointGroupingRule { XBreakpointGroupingByCategoryRule() { super("XBreakpointGroupingByCategoryRule", "Type"); } + @Override + public boolean isAlwaysEnabled() { + return true; + } + @Override public XBreakpointCategoryGroup getGroup(@NotNull B b, @NotNull Collection groups) { if (b instanceof Breakpoint) { diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointGroupingByClassRule.java b/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointGroupingByClassRule.java new file mode 100644 index 000000000000..aa28158221ae --- /dev/null +++ b/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointGroupingByClassRule.java @@ -0,0 +1,53 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.debugger.ui; + +import com.intellij.debugger.ui.breakpoints.Breakpoint; +import com.intellij.debugger.ui.breakpoints.BreakpointFactory; +import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroupingRule; +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; + +class XBreakpointGroupingByClassRule extends XBreakpointGroupingRule { + XBreakpointGroupingByClassRule() { + super("XBreakpointGroupingByClassRule", "Group by Class"); + } + + @Override + public boolean isAlwaysEnabled() { + return false; + } + + @Override + public XBreakpointClassGroup getGroup(@NotNull B b, @NotNull Collection groups) { + if (b instanceof Breakpoint) { + final Breakpoint breakpoint = (Breakpoint)b; + String className = breakpoint.getShortClassName(); + String packageName = breakpoint.getPackageName(); + if (className == null) { + return null; + } + for (XBreakpointClassGroup group : groups) { + if (group.getClassName().equals(className) && group.getPackageName().equals(packageName)) { + return group; + } + } + return new XBreakpointClassGroup(packageName, className); + } + return null; + } +} diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointGroupingByPackageRule.java b/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointGroupingByPackageRule.java new file mode 100644 index 000000000000..a9f43cc444ee --- /dev/null +++ b/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointGroupingByPackageRule.java @@ -0,0 +1,54 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.debugger.ui; + +import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter; +import com.intellij.debugger.ui.breakpoints.ExceptionBreakpoint; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroup; +import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroupingRule; +import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; + +public class XBreakpointGroupingByPackageRule extends XBreakpointGroupingRule { + + protected XBreakpointGroupingByPackageRule() { + super("XBreakpointGroupingByPackageRule", "Group by package"); + } + + @Override + public XBreakpointPackageGroup getGroup(@NotNull B breakpoint, @NotNull Collection groups) { + String packageName = null; + if (breakpoint instanceof BreakpointWithHighlighter) { + packageName = ((BreakpointWithHighlighter)breakpoint).getPackageName(); + } + else if (breakpoint instanceof ExceptionBreakpoint) { + packageName = ((ExceptionBreakpoint)breakpoint).getPackageName(); + } + if (packageName == null) { + return null; + } + for (XBreakpointPackageGroup group : groups) { + if (StringUtil.equals(group.getPackageName(), packageName)) { + return group; + } + } + return new XBreakpointPackageGroup(packageName); + } +} diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointPackageGroup.java b/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointPackageGroup.java new file mode 100644 index 000000000000..0d193a20255b --- /dev/null +++ b/java/debugger/impl/src/com/intellij/debugger/ui/XBreakpointPackageGroup.java @@ -0,0 +1,51 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.debugger.ui; + +import com.intellij.debugger.DebuggerBundle; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.util.PlatformIcons; +import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroup; +import org.jetbrains.annotations.NotNull; + +import javax.swing.*; + +public class XBreakpointPackageGroup extends XBreakpointGroup { + private static final String DEFAULT_PACKAGE_NAME = DebuggerBundle.message("default.package.name"); + + private String myPackageName; + + public XBreakpointPackageGroup(String packageName) { + myPackageName = packageName; + } + + @Override + public Icon getIcon(boolean isOpen) { + return PlatformIcons.PACKAGE_ICON; + } + + @NotNull + @Override + public String getName() { + String packageName = getPackageName(); + return StringUtil.isEmpty(packageName) ? DEFAULT_PACKAGE_NAME : packageName; + } + + @NotNull + public String getPackageName() { + return myPackageName; + } +} diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java index d99efc55bbb2..2d39fe03ead5 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java @@ -679,7 +679,7 @@ public class BreakpointTree extends CheckboxTree { if (!(descriptor instanceof BreakpointDescriptor)) { return node; } - + final Breakpoint breakpoint = ((BreakpointDescriptor)descriptor).getBreakpoint(); final String packageName; if (breakpoint instanceof ExceptionBreakpoint) { 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 2e52109b5ae4..7ef5417ca915 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 @@ -522,6 +522,7 @@ public abstract class BreakpointWithHighlighter extends Breakpoint { if (!highlighter.isValid()) { return null; } + highlighter.putUserData(DebuggerColors.BREAKPOINT_HIGHLIGHTER_KEY, Boolean.TRUE); highlighter.setErrorStripeTooltip(DebuggerBundle.message("breakpoint.tooltip.text", lineIndex + 1)); return highlighter; } diff --git a/java/debugger/openapi/src/com/intellij/debugger/engine/DebuggerUtils.java b/java/debugger/openapi/src/com/intellij/debugger/engine/DebuggerUtils.java index 382bcff89b41..96d684a289d3 100644 --- a/java/debugger/openapi/src/com/intellij/debugger/engine/DebuggerUtils.java +++ b/java/debugger/openapi/src/com/intellij/debugger/engine/DebuggerUtils.java @@ -334,19 +334,36 @@ public abstract class DebuggerUtils { return getSuperType(subType, superType) != null; } - public static PsiClass findClass(String className, Project project, final GlobalSearchScope scope) { + @Nullable + public static PsiClass findClass(final String className, Project project, final GlobalSearchScope scope) { ApplicationManager.getApplication().assertReadAccessAllowed(); final PsiManager psiManager = PsiManager.getInstance(project); + final JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(psiManager.getProject()); if (getArrayClass(className) != null) { - return JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().getArrayClass(LanguageLevelProjectExtension.getInstance(psiManager.getProject()).getLanguageLevel()); + return javaPsiFacade.getElementFactory().getArrayClass(LanguageLevelProjectExtension.getInstance(psiManager.getProject()).getLanguageLevel()); } if(project.isDefault()) { return null; } final String _className = className.replace('$', '.'); - final PsiClass aClass = JavaPsiFacade.getInstance(psiManager.getProject()).findClass(_className, scope); - if (aClass == null && scope != GlobalSearchScope.allScope(project)) { - return JavaPsiFacade.getInstance(psiManager.getProject()).findClass(_className, GlobalSearchScope.allScope(project)); + PsiClass aClass = javaPsiFacade.findClass(_className, scope); + if (aClass == null) { + if (!_className.equals(className)) { + // try original name if it differs from the normalized name + aClass = javaPsiFacade.findClass(className, scope); + } + } + if (aClass == null) { + final GlobalSearchScope globalScope = GlobalSearchScope.allScope(project); + if (!globalScope.equals(scope)) { + aClass = javaPsiFacade.findClass(_className, globalScope); + if (aClass == null) { + if (!_className.equals(className)) { + // try original name with global scope if the original differs from the normalized name + aClass = javaPsiFacade.findClass(className, globalScope); + } + } + } } return aClass; } diff --git a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/DownloadingOptionsDialog.java b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/DownloadingOptionsDialog.java index c5d6bde48e4c..f3b5ca2b3d2d 100644 --- a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/DownloadingOptionsDialog.java +++ b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/DownloadingOptionsDialog.java @@ -15,7 +15,7 @@ */ package com.intellij.facet.impl.ui.libraries; -import com.intellij.util.download.DownloadableFileDescription; +import com.intellij.framework.library.DownloadableLibraryFileDescription; import com.intellij.framework.library.DownloadableLibraryType; import com.intellij.framework.library.FrameworkLibraryVersion; import com.intellij.ide.ui.ListCellRendererWrapper; @@ -29,6 +29,7 @@ import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.ui.CheckBoxList; +import com.intellij.ui.CheckBoxListListener; import com.intellij.ui.CollectionListModel; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; @@ -47,6 +48,7 @@ import java.util.List; * @author Dmitry Avdeev */ public class DownloadingOptionsDialog extends DialogWrapper { + private static enum AdditionalDownloadType {SOURCES, DOCUMENTATION} private static final Logger LOG = Logger.getInstance("#com.intellij.facet.impl.ui.libraries.DownloadingOptionsDialog"); private JPanel myPanel; private CheckBoxList myFilesList; @@ -110,32 +112,79 @@ public class DownloadingOptionsDialog extends DialogWrapper { myCopyDownloadedFilesToLabel.setLabelFor(myDirectoryField); myDirectoryField.setText(FileUtil.toSystemDependentName(settings.getDirectoryForDownloadedLibrariesPath())); - //todo[nik] show when downloading sources/javadocs will be supported - myDownloadSourcesCheckBox.setVisible(false); - myDownloadJavadocsCheckBox.setVisible(false); + boolean sourcesCheckboxVisible = false; + boolean javadocCheckboxVisible = false; + for (FrameworkLibraryVersion version : versions) { + sourcesCheckboxVisible |= haveAdditionalDownloads(version.getFiles(), AdditionalDownloadType.SOURCES); + javadocCheckboxVisible |= haveAdditionalDownloads(version.getFiles(), AdditionalDownloadType.DOCUMENTATION); + } + myDownloadSourcesCheckBox.setVisible(sourcesCheckboxVisible); + myDownloadJavadocsCheckBox.setVisible(javadocCheckboxVisible); + myFilesList.setCheckBoxListListener(new CheckBoxListListener() { + @Override + public void checkBoxSelectionChanged(int index, boolean value) { + updateSourcesAndJavadocCheckboxes(); + } + }); + updateSourcesAndJavadocCheckboxes(); myDownloadSourcesCheckBox.setSelected(settings.isDownloadSources()); myDownloadJavadocsCheckBox.setSelected(settings.isDownloadJavaDocs()); init(); } - private void onVersionChanged(final @Nullable List selected) { + private void updateSourcesAndJavadocCheckboxes() { + final FrameworkLibraryVersion version = getSelectedVersion(); + boolean sourcesCheckboxEnabled; + boolean javadocCheckboxEnabled; + if (version == null) { + sourcesCheckboxEnabled = javadocCheckboxEnabled = false; + } + else { + final List descriptions = getSelectedDownloads(version); + sourcesCheckboxEnabled = haveAdditionalDownloads(descriptions, AdditionalDownloadType.SOURCES); + javadocCheckboxEnabled = haveAdditionalDownloads(descriptions, AdditionalDownloadType.DOCUMENTATION); + } + setEnabled(myDownloadSourcesCheckBox, sourcesCheckboxEnabled); + setEnabled(myDownloadJavadocsCheckBox, javadocCheckboxEnabled); + } + + private static void setEnabled(final JCheckBox checkBox, final boolean enabled) { + if (!enabled) { + checkBox.setSelected(false); + } + checkBox.setEnabled(enabled); + } + + private static boolean haveAdditionalDownloads(final List descriptions, AdditionalDownloadType type) { + for (DownloadableLibraryFileDescription description : descriptions) { + if (type == AdditionalDownloadType.SOURCES && description.getSourcesDescription() != null + || type == AdditionalDownloadType.DOCUMENTATION && description.getDocumentationDescription() != null) { + return true; + } + } + return false; + } + + private void onVersionChanged(final @Nullable List selectedFiles) { final FrameworkLibraryVersion version = getSelectedVersion(); if (Comparing.equal(myLastSelectedVersion, version)) return; if (version != null) { - final List downloads = version.getFiles(); - myFilesList.setModel(new CollectionListModel( - ContainerUtil.map2Array(downloads, JCheckBox.class, new Function() { + final List downloads = version.getFiles(); + myFilesList.setModel(new CollectionListModel( + ContainerUtil.map2Array(downloads, JCheckBox.class, new Function() { @Override - public JCheckBox fun(DownloadableFileDescription description) { - return new JCheckBox(description.getPresentableFileName(), selected == null || selected.contains(description)); + public JCheckBox fun(DownloadableLibraryFileDescription description) { + final boolean selected = selectedFiles != null ? selectedFiles.contains(description) : !description.isOptional(); + return new JCheckBox(description.getPresentableFileName(), selected); } }))); if (myNameAndLevelPanel != null) { myNameAndLevelPanel.setDefaultName(version.getDefaultLibraryName()); } } + updateSourcesAndJavadocCheckboxes(); myLastSelectedVersion = version; } @@ -168,9 +217,9 @@ public class DownloadingOptionsDialog extends DialogWrapper { return dialog.createSettings(); } - private List getSelectedDownloads(FrameworkLibraryVersion version) { - List selected = new ArrayList(); - List downloads = version.getFiles(); + private List getSelectedDownloads(FrameworkLibraryVersion version) { + List selected = new ArrayList(); + List downloads = version.getFiles(); for (int i = 0; i < downloads.size(); i++) { if (myFilesList.isItemSelected(i)) { selected.add(downloads.get(i)); @@ -194,7 +243,7 @@ public class DownloadingOptionsDialog extends DialogWrapper { } final String path = FileUtil.toSystemIndependentName(myDirectoryField.getText()); - List selected = getSelectedDownloads(version); + List selected = getSelectedDownloads(version); return new LibraryDownloadSettings(version, myLibraryType, path, libraryName, libraryLevel, selected, myDownloadSourcesCheckBox.isSelected(), myDownloadJavadocsCheckBox.isSelected()); diff --git a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryDownloadSettings.java b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryDownloadSettings.java index 2e12030dc85c..b3584169acfc 100644 --- a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryDownloadSettings.java +++ b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryDownloadSettings.java @@ -15,20 +15,28 @@ */ package com.intellij.facet.impl.ui.libraries; +import com.intellij.framework.library.DownloadableLibraryFileDescription; import com.intellij.framework.library.DownloadableLibraryType; import com.intellij.framework.library.FrameworkLibraryVersion; import com.intellij.framework.library.LibraryVersionProperties; +import com.intellij.openapi.roots.JavadocOrderRootType; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.ui.configuration.libraryEditor.NewLibraryEditor; import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer; +import com.intellij.openapi.util.Condition; +import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.download.DownloadableFileDescription; import com.intellij.util.download.DownloadableFileService; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** * @author nik @@ -41,19 +49,19 @@ public class LibraryDownloadSettings { private final boolean myDownloadSources; private final boolean myDownloadJavaDocs; private final LibrariesContainer.LibraryLevel myLibraryLevel; - private final List mySelectedDownloads; + private final List mySelectedDownloads; public LibraryDownloadSettings(@NotNull FrameworkLibraryVersion libraryVersion, @Nullable DownloadableLibraryType libraryType, final LibrariesContainer.LibraryLevel libraryLevel, final String downloadedLibrariesPath) { this(libraryVersion, libraryType, downloadedLibrariesPath, libraryVersion.getDefaultLibraryName(), libraryLevel, - libraryVersion.getFiles(), true, true); + getRequiredFiles(libraryVersion.getFiles()), true, true); } public LibraryDownloadSettings(@NotNull FrameworkLibraryVersion libraryVersion, @Nullable DownloadableLibraryType libraryType, @NotNull String directoryForDownloadedLibrariesPath, @NotNull String libraryName, @NotNull LibrariesContainer.LibraryLevel libraryLevel, - @NotNull List selectedDownloads, + @NotNull List selectedDownloads, boolean downloadSources, boolean downloadJavaDocs) { myVersion = libraryVersion; myLibraryType = libraryType; @@ -65,6 +73,15 @@ public class LibraryDownloadSettings { mySelectedDownloads = selectedDownloads; } + private static List getRequiredFiles(List files) { + return ContainerUtil.filter(files, new Condition() { + @Override + public boolean value(DownloadableLibraryFileDescription description) { + return !description.isOptional(); + } + }); + } + @NotNull public FrameworkLibraryVersion getVersion() { return myVersion; @@ -86,7 +103,7 @@ public class LibraryDownloadSettings { return myDirectoryForDownloadedLibrariesPath; } - public List getSelectedDownloads() { + public List getSelectedDownloads() { return mySelectedDownloads; } @@ -109,10 +126,26 @@ public class LibraryDownloadSettings { @Nullable public NewLibraryEditor download(JComponent parent) { - VirtualFile[] files = DownloadableFileService.getInstance().createDownloader(mySelectedDownloads, null, parent, myLibraryName + " Library") + final List toDownload = new ArrayList(mySelectedDownloads); + Map rootTypes = new HashMap(); + for (DownloadableLibraryFileDescription description : mySelectedDownloads) { + final DownloadableFileDescription sources = description.getSourcesDescription(); + if (myDownloadSources && sources != null) { + toDownload.add(sources); + rootTypes.put(sources, OrderRootType.SOURCES); + } + final DownloadableFileDescription docs = description.getDocumentationDescription(); + if (myDownloadJavaDocs && docs != null) { + toDownload.add(docs); + rootTypes.put(docs, JavadocOrderRootType.getInstance()); + } + } + + List> downloaded = + DownloadableFileService.getInstance().createDownloader(toDownload, null, parent, myLibraryName + " Library") .toDirectory(myDirectoryForDownloadedLibrariesPath) - .download(); - if (files == null) { + .downloadAndReturnWithDescriptions(); + if (downloaded == null) { return null; } @@ -124,8 +157,9 @@ public class LibraryDownloadSettings { libraryEditor = new NewLibraryEditor(); } libraryEditor.setName(myLibraryName); - for (VirtualFile file : files) { - libraryEditor.addRoot(file, OrderRootType.CLASSES); + for (Pair pair : downloaded) { + final OrderRootType rootType = rootTypes.containsKey(pair.getSecond()) ? rootTypes.get(pair.getSecond()) : OrderRootType.CLASSES; + libraryEditor.addRoot(pair.getFirst(), rootType); } return libraryEditor; } diff --git a/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/OldCustomLibraryDescription.java b/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/OldCustomLibraryDescription.java index bc2ab2fd62eb..7e53c09383d8 100644 --- a/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/OldCustomLibraryDescription.java +++ b/java/idea-ui/src/com/intellij/ide/util/frameworkSupport/OldCustomLibraryDescription.java @@ -19,16 +19,16 @@ import com.intellij.facet.impl.ui.libraries.RequiredLibrariesInfo; import com.intellij.facet.ui.libraries.LibraryDownloadInfo; import com.intellij.facet.ui.libraries.LibraryInfo; import com.intellij.framework.library.DownloadableLibraryDescription; +import com.intellij.framework.library.DownloadableLibraryFileDescription; import com.intellij.framework.library.FrameworkLibraryVersion; import com.intellij.framework.library.impl.DownloadableLibraryDescriptionImpl; +import com.intellij.framework.library.impl.DownloadableLibraryFileDescriptionImpl; import com.intellij.framework.library.impl.FrameworkLibraryVersionImpl; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryKind; import com.intellij.openapi.roots.ui.configuration.libraries.CustomLibraryDescription; import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer; -import com.intellij.util.download.DownloadableFileDescription; -import com.intellij.util.download.impl.DownloadableFileDescriptionImpl; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -53,13 +53,12 @@ public class OldCustomLibraryDescription extends CustomLibraryDescriptionBase { myVersions = versions; final List libraryVersions = new ArrayList(); for (FrameworkVersion version : versions) { - List downloads = new ArrayList(); + List downloads = new ArrayList(); for (LibraryInfo info : version.getLibraries()) { final LibraryDownloadInfo downloadingInfo = info.getDownloadingInfo(); if (downloadingInfo != null) { - final DownloadableFileDescription - element = new DownloadableFileDescriptionImpl(downloadingInfo.getDownloadUrl(), downloadingInfo.getFileNamePrefix(), downloadingInfo.getFileNameSuffix()); - downloads.add(element); + downloads.add(new DownloadableLibraryFileDescriptionImpl(downloadingInfo.getDownloadUrl(), downloadingInfo.getFileNamePrefix(), + downloadingInfo.getFileNameSuffix(), null, null, false)); } } libraryVersions.add(new FrameworkLibraryVersionImpl(version.getVersionName(), downloads, version.getLibraryName())); diff --git a/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileImpl.java b/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileImpl.java index 2e37a5d60f1a..36d2ba4e529b 100644 --- a/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileImpl.java +++ b/java/idea-ui/src/com/intellij/util/descriptors/impl/ConfigFileImpl.java @@ -1,7 +1,6 @@ package com.intellij.util.descriptors.impl; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener; @@ -43,7 +42,6 @@ public class ConfigFileImpl implements ConfigFile { } }); onChange(); - Disposer.register(container, this); myProject = myContainer.getProject(); } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/Java18CompletionData.java b/java/java-impl/src/com/intellij/codeInsight/completion/Java18CompletionData.java new file mode 100644 index 000000000000..d627fc535b0b --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/completion/Java18CompletionData.java @@ -0,0 +1,46 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.codeInsight.completion; + +import com.intellij.psi.PsiKeyword; +import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiParameterList; +import com.intellij.psi.filters.AndFilter; +import com.intellij.psi.filters.ClassFilter; +import com.intellij.psi.filters.ElementFilter; +import com.intellij.psi.filters.TextFilter; +import com.intellij.psi.filters.classes.InterfaceFilter; +import com.intellij.psi.filters.position.LeftNeighbour; +import com.intellij.psi.filters.position.ParentElementFilter; + +public class Java18CompletionData extends Java15CompletionData { + @Override + protected void initVariantsInMethodScope() { + super.initVariantsInMethodScope(); + + { + // in extension method + ElementFilter position = new AndFilter( + new LeftNeighbour(new AndFilter( + new TextFilter(")"), + new ParentElementFilter(new ClassFilter(PsiParameterList.class)))), + new ParentElementFilter(new InterfaceFilter(), 3)); + CompletionVariant variant = new CompletionVariant(PsiMethod.class, position); + variant.addCompletion(PsiKeyword.DEFAULT); + registerVariant(variant); + } + } +} diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java index 2e787a533784..a1e9fb3ce9f6 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.patterns.ElementPattern; import com.intellij.patterns.PatternCondition; import com.intellij.patterns.PsiNameValuePairPattern; +import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.filters.*; import com.intellij.psi.filters.classes.AssignableFromContextFilter; @@ -66,8 +67,22 @@ import static com.intellij.patterns.PsiJavaPatterns.*; public class JavaCompletionContributor extends CompletionContributor { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.JavaCompletionContributor"); - private static final Java15CompletionData ourJava15CompletionData = new Java15CompletionData(); - private static final JavaCompletionData ourJavaCompletionData = new JavaCompletionData(); + private static final Map ourCompletionData; + + static { + ourCompletionData = new LinkedHashMap(); + ourCompletionData.put(LanguageLevel.JDK_1_8, new Java18CompletionData()); + ourCompletionData.put(LanguageLevel.JDK_1_3, new Java15CompletionData()); + ourCompletionData.put(LanguageLevel.JDK_1_3, new JavaCompletionData()); + } + + private static JavaCompletionData getCompletionData(LanguageLevel level) { + final Set> entries = ourCompletionData.entrySet(); + for (Map.Entry entry : entries) { + if (entry.getKey().isAtLeast(level)) return entry.getValue(); + } + return ourCompletionData.get(LanguageLevel.JDK_1_3); + } private static final PsiNameValuePairPattern NAME_VALUE_PAIR = psiNameValuePair().withSuperParent(2, psiElement(PsiAnnotation.class)); @@ -338,7 +353,7 @@ public class JavaCompletionContributor extends CompletionContributor { PsiElement position = parameters.getPosition(); final Set lookupSet = new LinkedHashSet(); final Set keywordVariants = new HashSet(); - final JavaCompletionData completionData = PsiUtil.isLanguageLevel5OrHigher(position) ? ourJava15CompletionData : ourJavaCompletionData; + final JavaCompletionData completionData = getCompletionData(PsiUtil.getLanguageLevel(position)); completionData.addKeywordVariants(keywordVariants, position, parameters.getOriginalFile()); completionData.completeKeywordsBySet(lookupSet, keywordVariants, position, result.getPrefixMatcher(), parameters.getOriginalFile()); completionData.fillCompletions(parameters, result); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java index 618d7196e467..bb12266e5564 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -311,7 +311,7 @@ public class JavaCompletionData extends JavaAwareCompletionData{ } } - private void initVariantsInMethodScope() { + protected void initVariantsInMethodScope() { // Completion for classes in method throws section // position { @@ -363,7 +363,7 @@ public class JavaCompletionData extends JavaAwareCompletionData{ registerVariant(variant); } -// Catch/Finnaly completion +// Catch/Finally completion { final ElementFilter position = new LeftNeighbour(new AndFilter( new TextFilter("}"), diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java index 535aee6ea37b..a28be95d2166 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java @@ -678,6 +678,7 @@ public class HighlightClassUtil { * @param extendRef points to the class in the extends list * @param resolved extendRef resolved */ + @Nullable public static HighlightInfo checkClassExtendsForeignInnerClass(final PsiJavaCodeReferenceElement extendRef, final PsiElement resolved) { PsiElement parent = extendRef.getParent(); if (!(parent instanceof PsiReferenceList)) { @@ -723,11 +724,10 @@ public class HighlightClassUtil { // must be inner class if (!PsiUtil.isInnerClass(base)) return; - if (resolve == resolved) { - if (!hasEnclosingInstanceInScope(baseClass, extendRef, true) && !qualifiedNewCalledInConstructors(aClass, baseClass)) { - String description = JavaErrorMessages.message("no.enclosing.instance.in.scope", HighlightUtil.formatClass(baseClass)); - infos[0] = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, extendRef, description); - } + if (resolve == resolved && baseClass != null && + !hasEnclosingInstanceInScope(baseClass, extendRef, true) && !qualifiedNewCalledInConstructors(aClass, baseClass)) { + String description = JavaErrorMessages.message("no.enclosing.instance.in.scope", HighlightUtil.formatClass(baseClass)); + infos[0] = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, extendRef, description); } } } @@ -796,6 +796,7 @@ public class HighlightClassUtil { return checkCreateInnerClassFromStaticContext(expression, qualifier, aClass); } + @Nullable public static HighlightInfo checkCreateInnerClassFromStaticContext(PsiElement element, @Nullable PsiExpression qualifier, PsiClass aClass) { if (!PsiUtil.isInnerClass(aClass)) return null; PsiClass outerClass = aClass.getContainingClass(); @@ -803,15 +804,14 @@ public class HighlightClassUtil { PsiElement placeToSearchEnclosingFrom; if (qualifier != null) { - PsiType qtype = qualifier.getType(); - placeToSearchEnclosingFrom = PsiUtil.resolveClassInType(qtype); + PsiType qType = qualifier.getType(); + placeToSearchEnclosingFrom = PsiUtil.resolveClassInType(qType); } else { placeToSearchEnclosingFrom = element; } - if (outerClass instanceof JspClass - || hasEnclosingInstanceInScope(outerClass, placeToSearchEnclosingFrom, true)) return null; + if (outerClass instanceof JspClass || hasEnclosingInstanceInScope(outerClass, placeToSearchEnclosingFrom, true)) return null; return reportIllegalEnclosingUsage(placeToSearchEnclosingFrom, aClass, outerClass, element); } @@ -837,7 +837,8 @@ public class HighlightClassUtil { @Nullable public static HighlightInfo reportIllegalEnclosingUsage(PsiElement place, - PsiClass aClass, PsiClass outerClass, + @Nullable PsiClass aClass, + PsiClass outerClass, PsiElement elementToHighlight) { if (outerClass != null && !PsiTreeUtil.isContextAncestor(outerClass, place, false)) { String description = JavaErrorMessages.message("is.not.an.enclosing.class", HighlightUtil.formatClass(outerClass)); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java index ac3a5df3c7ad..618e5e8701ac 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java @@ -67,7 +67,7 @@ import static com.intellij.codeInsight.daemon.JavaHighlightingFilter.suppressed; /** * @author cdr - * Date: Jul 30, 2002 + * @since Jul 30, 2002 */ public class HighlightUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil"); @@ -534,14 +534,14 @@ public class HighlightUtil { IntentionAction fix = QUICK_FIX_FACTORY.createMethodReturnFix(method, valueType, true); QuickFixAction.registerQuickFixAction(errorResult, fix); } - } + } else { errorResult = checkAssignability(returnType, valueType, returnValue, statement); if (errorResult != null && valueType != null) { IntentionAction fix = QUICK_FIX_FACTORY.createMethodReturnFix(method, valueType, true); QuickFixAction.registerQuickFixAction(errorResult, fix); if (returnType instanceof PsiArrayType && TypeConversionUtil.isAssignable(((PsiArrayType)returnType).getComponentType(), valueType)) { - QuickFixAction.registerQuickFixAction(errorResult, new SurroundWithArrayFix(null){ + QuickFixAction.registerQuickFixAction(errorResult, new SurroundWithArrayFix(null) { @Override protected PsiExpression getExpression(final PsiElement element) { return returnValue.isValid() ? returnValue : null; @@ -580,7 +580,10 @@ public class HighlightUtil { private static String formatTypes(Collection unhandled) { return StringUtil.join(unhandled, new Function() { - @Override public String fun(PsiClassType type) { return formatType(type); } + @Override + public String fun(PsiClassType type) { + return formatType(type); + } }, ", "); } @@ -825,7 +828,8 @@ public class HighlightUtil { } else { if (PsiModifier.PUBLIC.equals(modifier)) { - isAllowed = modifierOwnerParent instanceof PsiJavaFile || (modifierOwnerParent instanceof PsiClass && (modifierOwnerParent instanceof JspClass || ((PsiClass)modifierOwnerParent).getQualifiedName() != null)); + isAllowed = modifierOwnerParent instanceof PsiJavaFile || + (modifierOwnerParent instanceof PsiClass && (modifierOwnerParent instanceof JspClass || ((PsiClass)modifierOwnerParent).getQualifiedName() != null)); } else if (PsiModifier.STATIC.equals(modifier) || PsiModifier.PRIVATE.equals(modifier) || PsiModifier.PROTECTED.equals(modifier) || PsiModifier.PACKAGE_LOCAL.equals(modifier)) { @@ -879,41 +883,30 @@ public class HighlightUtil { return null; } - @Nullable - static HighlightInfo checkLiteralExpressionParsingError(final PsiLiteralExpression expression) { - final String error = getLiteralExpressionParsingError(expression); - if (error != null) { - final HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, error); - QuickFixAction.registerQuickFixActions(info, getLiteralExpressionQuickFixes(expression)); - return info; - } - return null; - } - - private static final Key TOO_BIG_CHAR_LITERAL_KEY = Key.create("too.big.char.literal"); - - public static String getLiteralExpressionParsingError(final PsiLiteralExpression expression) { + public static HighlightInfo checkLiteralExpressionParsingError(final PsiLiteralExpression expression) { final Object value = expression.getValue(); final PsiElement literal = expression.getFirstChild(); assert literal instanceof PsiJavaToken : literal; final IElementType type = ((PsiJavaToken)literal).getTokenType(); String text = PsiLiteralExpressionImpl.NUMERIC_LITERALS.contains(type) ? literal.getText().toLowerCase() : literal.getText(); - final LanguageLevel languageLevel = PsiUtil.getLanguageLevel(expression); if (PsiLiteralExpressionImpl.REAL_LITERALS.contains(type)) { - if (text.startsWith(PsiLiteralExpressionImpl.HEX_PREFIX) && !languageLevel.isAtLeast(LanguageLevel.JDK_1_5)) { - return JavaErrorMessages.message("hex.FP.literals.not.supported"); + if (text.startsWith(PsiLiteralExpressionImpl.HEX_PREFIX)) { + final HighlightInfo info = checkFeature(expression, Feature.HEX_FP_LITERALS); + if (info != null) return info; } } if (PsiLiteralExpressionImpl.INTEGER_LITERALS.contains(type)) { - if (text.startsWith(PsiLiteralExpressionImpl.BIN_PREFIX) && !languageLevel.isAtLeast(LanguageLevel.JDK_1_7)) { - return JavaErrorMessages.message("binary.literals.not.supported"); + if (text.startsWith(PsiLiteralExpressionImpl.BIN_PREFIX)) { + final HighlightInfo info = checkFeature(expression, Feature.BIN_LITERALS); + if (info != null) return info; } } if (PsiLiteralExpressionImpl.NUMERIC_LITERALS.contains(type)) { - if (text.contains("_") && !languageLevel.isAtLeast(LanguageLevel.JDK_1_7)) { - return JavaErrorMessages.message("underscores.in.literals.not.supported"); + if (text.contains("_")) { + final HighlightInfo info = checkFeature(expression, Feature.UNDERSCORES); + if (info != null) return info; } } @@ -924,13 +917,16 @@ public class HighlightUtil { parent instanceof PsiPrefixExpression && ((PsiPrefixExpression)parent).getOperationTokenType() == JavaTokenType.MINUS)) { if (text.equals(PsiLiteralExpressionImpl.HEX_PREFIX)) { - return JavaErrorMessages.message("hexadecimal.numbers.must.contain.at.least.one.hexadecimal.digit"); + final String message = JavaErrorMessages.message("hexadecimal.numbers.must.contain.at.least.one.hexadecimal.digit"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); } if (text.equals(PsiLiteralExpressionImpl.BIN_PREFIX)) { - return JavaErrorMessages.message("binary.numbers.must.contain.at.least.one.hexadecimal.digit"); + final String message = JavaErrorMessages.message("binary.numbers.must.contain.at.least.one.hexadecimal.digit"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); } if (value == null || text.equals(PsiLiteralExpressionImpl._2_IN_31)) { - return JavaErrorMessages.message("integer.number.too.large"); + final String message = JavaErrorMessages.message("integer.number.too.large"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); } } } @@ -941,19 +937,23 @@ public class HighlightUtil { parent instanceof PsiPrefixExpression && ((PsiPrefixExpression)parent).getOperationTokenType() == JavaTokenType.MINUS)) { if (mText.equals(PsiLiteralExpressionImpl.HEX_PREFIX)) { - return JavaErrorMessages.message("hexadecimal.numbers.must.contain.at.least.one.hexadecimal.digit"); + final String message = JavaErrorMessages.message("hexadecimal.numbers.must.contain.at.least.one.hexadecimal.digit"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); } if (mText.equals(PsiLiteralExpressionImpl.BIN_PREFIX)) { - return JavaErrorMessages.message("binary.numbers.must.contain.at.least.one.hexadecimal.digit"); + final String message = JavaErrorMessages.message("binary.numbers.must.contain.at.least.one.hexadecimal.digit"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); } if (value == null || mText.equals(PsiLiteralExpressionImpl._2_IN_63)) { - return JavaErrorMessages.message("long.number.too.large"); + final String message = JavaErrorMessages.message("long.number.too.large"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); } } } else if (type == JavaTokenType.FLOAT_LITERAL || type == JavaTokenType.DOUBLE_LITERAL) { if (value == null) { - return JavaErrorMessages.message("malformed.floating.point.literal"); + final String message = JavaErrorMessages.message("malformed.floating.point.literal"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); } } else if (type == JavaTokenType.TRUE_KEYWORD || type == JavaTokenType.FALSE_KEYWORD || type == JavaTokenType.NULL_KEYWORD) { @@ -962,28 +962,41 @@ public class HighlightUtil { else if (type == JavaTokenType.CHARACTER_LITERAL) { // todo[r.sh] clean this mess up if (value != null) { - if (!StringUtil.endsWithChar(text, '\'')) return JavaErrorMessages.message("unclosed.char.literal"); + if (!StringUtil.endsWithChar(text, '\'')) { + final String message = JavaErrorMessages.message("unclosed.char.literal"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); + } } else { if (!StringUtil.startsWithChar(text, '\'')) return null; if (StringUtil.endsWithChar(text, '\'')) { - if (text.length() == 1) return JavaErrorMessages.message("illegal.line.end.in.character.literal"); + if (text.length() == 1) { + final String message = JavaErrorMessages.message("illegal.line.end.in.character.literal"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); + } text = text.substring(1, text.length() - 1); } else { - return JavaErrorMessages.message("illegal.line.end.in.character.literal"); + final String message = JavaErrorMessages.message("illegal.line.end.in.character.literal"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); } final StringBuilder chars = StringBuilderSpinAllocator.alloc(); final boolean success = PsiLiteralExpressionImpl.parseStringCharacters(text, chars, null); - if (!success) return JavaErrorMessages.message("illegal.escape.character.in.character.literal"); + if (!success) { + final String message = JavaErrorMessages.message("illegal.escape.character.in.character.literal"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); + } final int length = chars.length(); StringBuilderSpinAllocator.dispose(chars); if (length > 1) { - literal.putUserData(TOO_BIG_CHAR_LITERAL_KEY, Boolean.TRUE); - return JavaErrorMessages.message("too.many.characters.in.character.literal"); + final String message = JavaErrorMessages.message("too.many.characters.in.character.literal"); + final HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); + QuickFixAction.registerQuickFixAction(info, new ConvertToStringLiteralAction()); + return info; } else if (length == 0) { - return JavaErrorMessages.message("empty.character.literal"); + final String message = JavaErrorMessages.message("empty.character.literal"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); } } } @@ -997,27 +1010,46 @@ public class HighlightUtil { if (!StringUtil.startsWithChar(text, '\"')) return null; if (StringUtil.endsWithChar(text, '\"')) { - if (text.length() == 1) return JavaErrorMessages.message("illegal.line.end.in.string.literal"); + if (text.length() == 1) { + final String message = JavaErrorMessages.message("illegal.line.end.in.string.literal"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); + } text = text.substring(1, text.length() - 1); } else { - return JavaErrorMessages.message("illegal.line.end.in.string.literal"); + final String message = JavaErrorMessages.message("illegal.line.end.in.string.literal"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); } StringBuilder chars = new StringBuilder(); boolean success = PsiLiteralExpressionImpl.parseStringCharacters(text, chars, null); - if (!success) return JavaErrorMessages.message("illegal.escape.character.in.string.literal"); + if (!success) { + final String message = JavaErrorMessages.message("illegal.escape.character.in.string.literal"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); + } } } if (value instanceof Float) { final Float number = (Float)value; - if (number.isInfinite()) return JavaErrorMessages.message("floating.point.number.too.large"); - if (number.floatValue() == 0 && !isFPZero(text)) return JavaErrorMessages.message("floating.point.number.too.small"); + if (number.isInfinite()) { + final String message = JavaErrorMessages.message("floating.point.number.too.large"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); + } + if (number.floatValue() == 0 && !isFPZero(text)) { + final String message = JavaErrorMessages.message("floating.point.number.too.small"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); + } } else if (value instanceof Double) { final Double number = (Double)value; - if (number.isInfinite()) return JavaErrorMessages.message("floating.point.number.too.large"); - if (number.doubleValue() == 0 && !isFPZero(text)) return JavaErrorMessages.message("floating.point.number.too.small"); + if (number.isInfinite()) { + final String message = JavaErrorMessages.message("floating.point.number.too.large"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); + } + if (number.doubleValue() == 0 && !isFPZero(text)) { + final String message = JavaErrorMessages.message("floating.point.number.too.small"); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); + } } return null; @@ -1033,33 +1065,6 @@ public class HighlightUtil { return true; } - private static Collection getLiteralExpressionQuickFixes(final PsiLiteralExpression expression) { - final PsiElement literal = expression.getFirstChild(); - assert literal instanceof PsiJavaToken : literal; - final String text = literal.getText().toLowerCase(); - final IElementType type = ((PsiJavaToken)literal).getTokenType(); - final LanguageLevel languageLevel = PsiUtil.getLanguageLevel(expression); - - if (PsiLiteralExpressionImpl.REAL_LITERALS.contains(type)) { - if (!languageLevel.isAtLeast(LanguageLevel.JDK_1_5) && text.startsWith(PsiLiteralExpressionImpl.HEX_PREFIX)) { - return Collections.singletonList(new IncreaseLanguageLevelFix(LanguageLevel.JDK_1_5)); - } - } - if (PsiLiteralExpressionImpl.NUMERIC_LITERALS.contains(type)) { - if (!languageLevel.isAtLeast(LanguageLevel.JDK_1_7) && (text.startsWith(PsiLiteralExpressionImpl.BIN_PREFIX) || text.contains("_"))) { - return Collections.singletonList(new IncreaseLanguageLevelFix(LanguageLevel.JDK_1_7)); - } - } - if (type == JavaTokenType.CHARACTER_LITERAL) { - if (Boolean.TRUE.equals(literal.getUserData(TOO_BIG_CHAR_LITERAL_KEY))) { - return Collections.singletonList(new ConvertToStringLiteralAction()); - } - } - - return Collections.emptyList(); - } - - @Nullable static HighlightInfo checkMustBeBoolean(@NotNull PsiExpression expr, PsiType type) { PsiElement parent = expr.getParent(); @@ -1071,7 +1076,7 @@ public class HighlightUtil { if (!TypeConversionUtil.isBooleanType(type)) { final HighlightInfo info = createIncompatibleTypeHighlightInfo(PsiType.BOOLEAN, type, expr.getTextRange()); if (expr instanceof PsiMethodCallExpression) { - final PsiMethodCallExpression methodCall = (PsiMethodCallExpression) expr; + final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)expr; final PsiMethod method = methodCall.resolveMethod(); if (method != null && PsiType.VOID.equals(method.getReturnType())) { IntentionAction fix = QUICK_FIX_FACTORY.createMethodReturnFix(method, PsiType.BOOLEAN, true); @@ -1140,8 +1145,7 @@ public class HighlightUtil { final List typeElements = PsiUtil.getParameterTypeElements(parameter); final Collection highlights = Lists.newArrayListWithCapacity(typeElements.size()); - for (int i = 0, size = typeElements.size(); i < size; i++) { - final PsiTypeElement typeElement = typeElements.get(i); + for (final PsiTypeElement typeElement : typeElements) { final PsiType catchType = typeElement.getType(); if (catchType instanceof PsiClassType && ExceptionUtil.isUncheckedExceptionOrSuperclass((PsiClassType)catchType)) continue; @@ -1188,7 +1192,10 @@ public class HighlightUtil { // collect exceptions which are caught by this type Collection caught = ContainerUtil.findAll(thrownTypes, new Condition() { - @Override public boolean value(PsiClassType type) { return catchType.isAssignableFrom(type); } + @Override + public boolean value(PsiClassType type) { + return catchType.isAssignableFrom(type); + } }); if (caught.isEmpty()) continue; final Collection caughtCopy = Sets.newHashSet(caught); @@ -1247,7 +1254,8 @@ public class HighlightUtil { if (PsiType.LONG.equals(type) || PsiType.FLOAT.equals(type) || PsiType.DOUBLE.equals(type)) { QuickFixAction.registerQuickFixAction(errorResult, new AddTypeCastFix(PsiType.INT, expression)); } - } else { + } + else { final PsiClass member = PsiUtil.resolveClassInClassTypeOnly(type); if (member != null && !PsiUtil.isAccessible(member, expression, null)) { String message = PsiFormatUtil.formatClass(member, PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_FQ_NAME) + " is inaccessible here"; @@ -1285,8 +1293,8 @@ public class HighlightUtil { if (!TypeConversionUtil.isBinaryOperatorApplicable(operationSign, lType, rType, false)) { PsiJavaToken token = expression.getTokenBeforeOperand(operand); String message = JavaErrorMessages.message("binary.operator.not.applicable", token.getText(), - formatType(lType), - formatType(rType)); + formatType(lType), + formatType(rType)); return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, message); } lType = TypeConversionUtil.calcTypeForBinaryExpression(lType, rType, operationSign, true); @@ -1314,29 +1322,56 @@ public class HighlightUtil { } @Nullable - public static HighlightInfo checkThisOrSuperExpressionInIllegalContext(PsiExpression expr, @Nullable PsiJavaCodeReferenceElement qualifier) { - if (expr instanceof PsiSuperExpression && !(expr.getParent() instanceof PsiReferenceExpression)) { - // like in 'Object o = super;' - return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expr.getTextRange().getEndOffset(), - expr.getTextRange().getEndOffset() + 1, - JavaErrorMessages.message("dot.expected.after.super.or.this")); + public static HighlightInfo checkThisOrSuperExpressionInIllegalContext(PsiExpression expr, + @Nullable PsiJavaCodeReferenceElement qualifier) { + if (expr instanceof PsiSuperExpression) { + final PsiElement parent = expr.getParent(); + if (!(parent instanceof PsiReferenceExpression)) { + // like in 'Object o = super;' + final int o = expr.getTextRange().getEndOffset(); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, o, o + 1, JavaErrorMessages.message("dot.expected.after.super.or.this")); + } + + if (PsiUtil.isLanguageLevel8OrHigher(expr)) { + final PsiMethod method = PsiTreeUtil.getParentOfType(expr, PsiMethod.class); + if (PsiUtil.isExtensionMethod(method) && qualifier == null) { + //todo[r.sh] "Add qualifier" quick fix + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, parent, JavaErrorMessages.message("unqualified.super.disallowed")); + } + } } - PsiElement resolved = null; - PsiClass aClass = qualifier == null ? PsiTreeUtil.getParentOfType(expr, PsiClass.class) : (resolved = qualifier.resolve()) instanceof PsiClass ? (PsiClass)resolved : null; - if (resolved != null && !(resolved instanceof PsiClass)) { - return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, qualifier, JavaErrorMessages.message("class.expected")); + + final PsiClass aClass; + if (qualifier != null) { + final PsiElement resolved = qualifier.resolve(); + if (resolved != null && !(resolved instanceof PsiClass)) { + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, qualifier, JavaErrorMessages.message("class.expected")); + } + aClass = (PsiClass)resolved; + } + else { + aClass = PsiTreeUtil.getParentOfType(expr, PsiClass.class); } if (aClass == null) return null; - if (qualifier != null && aClass.isInterface()) { - return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, qualifier, JavaErrorMessages.message("no.interface.expected")); - } - if (!HighlightClassUtil.hasEnclosingInstanceInScope(aClass, expr, false)) { + + if (!HighlightClassUtil.hasEnclosingInstanceInScope(aClass, expr, false) && + !resolvesToImmediateSuperInterface(expr, qualifier, aClass)) { return HighlightClassUtil.reportIllegalEnclosingUsage(expr, null, aClass, expr); } return null; } + private static boolean resolvesToImmediateSuperInterface(PsiExpression expr, + @Nullable PsiJavaCodeReferenceElement qualifier, + PsiClass aClass) { + if (!(expr instanceof PsiSuperExpression) || qualifier == null || !PsiUtil.isLanguageLevel8OrHigher(expr)) return false; + final PsiType superType = expr.getType(); + if (!(superType instanceof PsiClassType)) return false; + final PsiClass superClass = ((PsiClassType)superType).resolve(); + return superClass != null && aClass.equals(superClass); + } + static String buildProblemWithStaticDescription(PsiElement refElement) { String type = LanguageFindUsages.INSTANCE.forLanguage(JavaLanguage.INSTANCE).getType(refElement); String name = HighlightMessageUtil.getSymbolName(refElement, PsiSubstitutor.EMPTY); @@ -1406,13 +1441,19 @@ public class HighlightUtil { } @Nullable - static HighlightInfo checkValidArrayAccessExpression(@Nullable PsiExpression arrayExpression, PsiExpression indexExpression, PsiType type) { - PsiType arrayExpressionType = arrayExpression == null ? null : arrayExpression.getType(); + static HighlightInfo checkValidArrayAccessExpression(@NotNull PsiArrayAccessExpression arrayAccessExpression) { + final PsiExpression arrayExpression = arrayAccessExpression.getArrayExpression(); + final PsiType arrayExpressionType = arrayExpression.getType(); + if (arrayExpressionType != null && !(arrayExpressionType instanceof PsiArrayType)) { - String description = JavaErrorMessages.message("array.type.expected", formatType(arrayExpressionType)); - return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, arrayExpression, description); + final String description = JavaErrorMessages.message("array.type.expected", formatType(arrayExpressionType)); + final HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, arrayExpression, description); + QuickFixAction.registerQuickFixAction(info, new ReplaceWithListAccessFix(arrayAccessExpression)); + return info; } - return checkAssignability(PsiType.INT, indexExpression.getType(), indexExpression, indexExpression); + + final PsiExpression indexExpression = arrayAccessExpression.getIndexExpression(); + return indexExpression != null ? checkAssignability(PsiType.INT, indexExpression.getType(), indexExpression, indexExpression) : null; } @@ -1440,8 +1481,8 @@ public class HighlightUtil { if (!(initializer instanceof PsiArrayInitializerExpression)) return null; if (!(type instanceof PsiArrayType)) return null; - final PsiType componentType = ((PsiArrayType) type).getComponentType(); - final PsiArrayInitializerExpression arrayInitializer = (PsiArrayInitializerExpression) initializer; + final PsiType componentType = ((PsiArrayType)type).getComponentType(); + final PsiArrayInitializerExpression arrayInitializer = (PsiArrayInitializerExpression)initializer; boolean arrayTypeFixChecked = false; VariableArrayTypeFix fix = null; @@ -1535,7 +1576,8 @@ public class HighlightUtil { return null; } - HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, JavaErrorMessages.message("array.initializer.not.allowed")); + HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, + JavaErrorMessages.message("array.initializer.not.allowed")); QuickFixAction.registerQuickFixAction(info, new AddNewArrayExpressionFix(expression)); return info; } @@ -1617,7 +1659,7 @@ public class HighlightUtil { String description = JavaErrorMessages.message("switch.colon.expected.after.case.label"); CharSequence chars = statement.getContainingFile().getViewProvider().getContents(); boolean isAfterEndOfLine = end >= chars.length() || chars.charAt(start) == '\n' || chars.charAt(start) == '\r'; - return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, null,start, end, description, description,isAfterEndOfLine, null); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, null, start, end, description, description, isAfterEndOfLine, null); } return null; } @@ -1709,10 +1751,10 @@ public class HighlightUtil { if (((PsiMethod)typeOwner).getReturnTypeElement() == parent) return null; } else if (// like in Class c = void.class; - typeOwner instanceof PsiClassObjectAccessExpression && - TypeConversionUtil.isVoidType(((PsiClassObjectAccessExpression)typeOwner).getOperand().getType()) || - // do not highlight incomplete declarations - typeOwner != null && PsiUtilCore.hasErrorElementChild(typeOwner)) { + typeOwner instanceof PsiClassObjectAccessExpression && + TypeConversionUtil.isVoidType(((PsiClassObjectAccessExpression)typeOwner).getOperand().getType()) || + // do not highlight incomplete declarations + typeOwner != null && PsiUtilCore.hasErrorElementChild(typeOwner)) { return null; } else if (typeOwner instanceof JavaCodeFragment) { @@ -1733,7 +1775,9 @@ public class HighlightUtil { // redirected ctr if (PsiKeyword.THIS.equals(((PsiJavaCodeReferenceElement)expression).getReferenceName()) && resolved instanceof PsiMethod - && ((PsiMethod)resolved).isConstructor()) return null; + && ((PsiMethod)resolved).isConstructor()) { + return null; + } PsiElement qualifier = ((PsiJavaCodeReferenceElement)expression).getQualifier(); type = qualifier instanceof PsiExpression ? ((PsiExpression)qualifier).getType() : null; referencedClass = PsiUtil.resolveClassInType(type); @@ -1785,7 +1829,7 @@ public class HighlightUtil { resolvedName = qualifier.getText(); } } - else if (PsiKeyword.THIS.equals(name)) { + else if (PsiKeyword.THIS.equals(name)) { resolvedName = PsiKeyword.THIS; } else { @@ -1891,11 +1935,11 @@ public class HighlightUtil { PsiMethod[] constructors = aClass.getConstructors(); if (constructors.length == 0) { TextRange range = HighlightNamesUtil.getClassDeclarationTextRange(aClass); - return createMemberReferencedError(aClass.getName()+".this", range); + return createMemberReferencedError(aClass.getName() + ".this", range); } for (PsiMethod constructor : constructors) { if (!isSuperCalledInConstructor(constructor)) { - return createMemberReferencedError(aClass.getName()+".this", HighlightNamesUtil.getMethodDeclarationTextRange(constructor)); + return createMemberReferencedError(aClass.getName() + ".this", HighlightNamesUtil.getMethodDeclarationTextRange(constructor)); } } return null; @@ -1908,12 +1952,12 @@ public class HighlightUtil { if (statements.length == 0) return false; final PsiStatement statement = statements[0]; final PsiElement element = new PsiMatcherImpl(statement) - .dot(PsiMatchers.hasClass(PsiExpressionStatement.class)) - .firstChild(PsiMatchers.hasClass(PsiMethodCallExpression.class)) - .firstChild(PsiMatchers.hasClass(PsiReferenceExpression.class)) - .firstChild(PsiMatchers.hasClass(PsiKeyword.class)) - .dot(PsiMatchers.hasText(PsiKeyword.SUPER)) - .getElement(); + .dot(PsiMatchers.hasClass(PsiExpressionStatement.class)) + .firstChild(PsiMatchers.hasClass(PsiMethodCallExpression.class)) + .firstChild(PsiMatchers.hasClass(PsiReferenceExpression.class)) + .firstChild(PsiMatchers.hasClass(PsiKeyword.class)) + .dot(PsiMatchers.hasText(PsiKeyword.SUPER)) + .getElement(); return element != null; } @@ -1923,10 +1967,12 @@ public class HighlightUtil { PsiReferenceExpression methodExpression = ((PsiMethodCallExpression)element).getMethodExpression(); return methodExpression.getReferenceName(); } + public static boolean isSuperOrThisMethodCall(PsiElement element) { String name = getMethodExpressionName(element); return PsiKeyword.SUPER.equals(name) || PsiKeyword.THIS.equals(name); } + public static boolean isSuperMethodCall(PsiElement element) { String name = getMethodExpressionName(element); return PsiKeyword.SUPER.equals(name); @@ -2362,7 +2408,8 @@ public class HighlightUtil { } if ((resolved instanceof PsiLocalVariable || resolved instanceof PsiParameter) && !(resolved instanceof ImplicitVariable)) { highlightInfo = HighlightControlFlowUtil.checkVariableMustBeFinal((PsiVariable)resolved, ref); - } else if (resolved instanceof PsiClass) { + } + else if (resolved instanceof PsiClass) { if (Comparing.strEqual(((PsiClass)resolved).getQualifiedName(), ((PsiClass)resolved).getName())) { final PsiElement parent = ref.getParent(); if (parent instanceof PsiImportStaticReferenceElement || parent instanceof PsiImportStatementBase) { @@ -2391,8 +2438,8 @@ public class HighlightUtil { @Nullable public static HighlightInfo checkElementInReferenceList(PsiJavaCodeReferenceElement ref, - PsiReferenceList referenceList, - JavaResolveResult resolveResult) { + PsiReferenceList referenceList, + JavaResolveResult resolveResult) { PsiElement resolved = resolveResult.getElement(); HighlightInfo highlightInfo = null; PsiElement refGrandParent = referenceList.getParent(); @@ -2478,9 +2525,12 @@ public class HighlightUtil { STATIC_IMPORTS(LanguageLevel.JDK_1_5, "feature.static.imports"), FOR_EACH(LanguageLevel.JDK_1_5, "feature.for.each"), VARARGS(LanguageLevel.JDK_1_5, "feature.varargs"), + HEX_FP_LITERALS(LanguageLevel.JDK_1_5, "feature.hex.fp.literals"), DIAMOND_TYPES(LanguageLevel.JDK_1_7, "feature.diamond.types"), MULTI_CATCH(LanguageLevel.JDK_1_7, "feature.multi.catch"), TRY_WITH_RESOURCES(LanguageLevel.JDK_1_7, "feature.try.with.resources"), + BIN_LITERALS(LanguageLevel.JDK_1_7, "feature.binary.literals"), + UNDERSCORES(LanguageLevel.JDK_1_7, "feature.underscores.in.literals"), EXTENSION_METHODS(LanguageLevel.JDK_1_8, "feature.extension.methods"); private final LanguageLevel level; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java index 4de3dad216db..23d6ccbfc79b 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java @@ -79,7 +79,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh } } }; - + public HighlightVisitorImpl(@NotNull PsiResolveHelper resolveHelper) { myResolveHelper = resolveHelper; } @@ -93,7 +93,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh @Override public int order() { return 0; - } + } @Override public boolean suitableForFile(@NotNull PsiFile file) { @@ -324,22 +324,20 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh @Override public void visitExpression(PsiExpression expression) { ProgressManager.checkCanceled(); // visitLiteralExpression is invoked very often in array initializers - + super.visitExpression(expression); PsiType type = expression.getType(); if (myHolder.add(HighlightUtil.checkMustBeBoolean(expression, type))) return; - PsiExpression indexExpression; - if (expression instanceof PsiArrayAccessExpression - && (indexExpression = ((PsiArrayAccessExpression)expression).getIndexExpression()) != null) { - PsiExpression arrayExpression = ((PsiArrayAccessExpression)expression).getArrayExpression(); - myHolder.add(HighlightUtil.checkValidArrayAccessExpression(arrayExpression, indexExpression, indexExpression.getType())); + if(expression instanceof PsiArrayAccessExpression) { + myHolder.add(HighlightUtil.checkValidArrayAccessExpression((PsiArrayAccessExpression)expression)); } + if (expression.getParent() instanceof PsiNewExpression && ((PsiNewExpression)expression.getParent()).getQualifier() != expression && ((PsiNewExpression)expression.getParent()).getArrayInitializer() != expression) { // like in 'new String["s"]' - myHolder.add(HighlightUtil.checkValidArrayAccessExpression(null, expression, type)); + myHolder.add(HighlightUtil.checkAssignability(PsiType.INT, expression.getType(), expression, expression)); } if (!myHolder.hasErrorResults()) myHolder.add(HighlightControlFlowUtil.checkCannotWriteToFinal(expression)); if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkVariableExpected(expression)); @@ -900,7 +898,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh if (!(parent instanceof PsiTypeParameter)) { myHolder.add(AnnotationsHighlightUtil.checkAnnotationDeclaration(parent, list)); if (!myHolder.hasErrorResults()) myHolder.add(HighlightClassUtil.checkExtendsAllowed(list)); - if (!myHolder.hasErrorResults()) myHolder.add(HighlightClassUtil.checkImplementsAllowed(list)); + if (!myHolder.hasErrorResults()) myHolder.add(HighlightClassUtil.checkImplementsAllowed(list)); if (!myHolder.hasErrorResults()) myHolder.add(HighlightClassUtil.checkClassExtendsOnlyOneClass(list)); if (!myHolder.hasErrorResults()) myHolder.add(GenericsHighlightUtil.checkGenericCannotExtendException(list)); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ReplaceWithListAccessFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ReplaceWithListAccessFix.java new file mode 100644 index 000000000000..4a73cb1daf69 --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ReplaceWithListAccessFix.java @@ -0,0 +1,142 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.codeInsight.daemon.impl.quickfix; + +import com.intellij.codeInsight.CodeInsightUtilBase; +import com.intellij.codeInsight.daemon.QuickFixBundle; +import com.intellij.codeInsight.intention.IntentionAction; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.psi.codeStyle.CodeStyleManager; +import com.intellij.psi.util.TypeConversionUtil; +import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * @author Danila Ponomarenko + */ +public class ReplaceWithListAccessFix implements IntentionAction { + private PsiArrayAccessExpression myArrayAccessExpression; + + public ReplaceWithListAccessFix(PsiArrayAccessExpression arrayAccessExpression) { + myArrayAccessExpression = arrayAccessExpression; + } + + @NotNull + @Override + public String getText() { + return QuickFixBundle.message("replace.with.list.access.text"); + } + + @NotNull + @Override + public String getFamilyName() { + return getText(); + } + + @Override + public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { + if (!myArrayAccessExpression.isValid()) return false; + if (!TypeConversionUtil.areTypesAssignmentCompatible(PsiType.INT, myArrayAccessExpression.getIndexExpression())) { + return false; + } + final PsiElement parent = myArrayAccessExpression.getParent(); + if (parent instanceof PsiAssignmentExpression) { + final PsiExpression lExpression = ((PsiAssignmentExpression)parent).getLExpression(); + if (lExpression.equals(myArrayAccessExpression) && !(parent.getParent() instanceof PsiExpressionStatement)) { + return false; + } + } + + final PsiExpression arrayExpression = myArrayAccessExpression.getArrayExpression(); + final PsiType type = arrayExpression.getType(); + final PsiType listType = createUtilListType(project); + + if (type == null || listType == null) return false; + + + return listType.isAssignableFrom(type); + } + + @Nullable + private PsiType createUtilListType(@NotNull Project project) { + final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); + final PsiClass listClass = JavaPsiFacade.getInstance(project).findClass(CommonClassNames.JAVA_UTIL_LIST, myArrayAccessExpression.getResolveScope()); + + if (listClass == null) return null; + + final PsiElementFactory factory = facade.getElementFactory(); + return factory.createType(listClass); + } + + @Override + public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { + if (!CodeInsightUtilBase.prepareFileForWrite(file)) return; + final PsiExpression arrayExpression = myArrayAccessExpression.getArrayExpression(); + final PsiExpression indexExpression = myArrayAccessExpression.getIndexExpression(); + + if (indexExpression == null) return; + + final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); + final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); + + final PsiElement parent = myArrayAccessExpression.getParent(); + if (parent instanceof PsiAssignmentExpression) { + final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)parent; + + final PsiExpression lExpression = assignmentExpression.getLExpression(); + final PsiExpression rExpression = assignmentExpression.getRExpression(); + if (lExpression.equals(myArrayAccessExpression) && parent.getParent() instanceof PsiExpressionStatement && rExpression != null) { + replaceWithSet(factory, codeStyleManager, arrayExpression, indexExpression, rExpression, assignmentExpression); + return; + } + } + replaceWithGet(factory, codeStyleManager, arrayExpression, indexExpression, myArrayAccessExpression); + } + + @NotNull + private static PsiElement replaceWithGet(@NotNull PsiElementFactory factory, + @NotNull CodeStyleManager codeStyleManager, + @NotNull PsiExpression arrayExpression, + @NotNull PsiExpression indexExpression, + @NotNull PsiElement anchor) { + + final PsiElement listAccess = factory.createExpressionFromText( + arrayExpression.getText() + ".get(" + indexExpression.getText() + ")", + anchor); + return anchor.replace(codeStyleManager.reformat(listAccess)); + } + + private static PsiElement replaceWithSet(@NotNull PsiElementFactory factory, + @NotNull CodeStyleManager codeStyleManager, + @NotNull PsiExpression arrayExpression, + @NotNull PsiExpression indexExpression, + @NotNull PsiExpression expression, + @NotNull PsiElement anchor) { + final PsiElement listAccess = factory.createExpressionFromText( + arrayExpression.getText() + ".set(" + indexExpression.getText() + "," + expression.getText() + ")", + anchor + ); + return anchor.replace(codeStyleManager.reformat(listAccess)); + } + + @Override + public boolean startInWriteAction() { + return true; + } +} diff --git a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java index e183c5d8e9da..38c51a4acc66 100644 --- a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java +++ b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java @@ -267,7 +267,7 @@ public class JavaFoldingBuilder extends CustomFoldingBuilder implements DumbAwar PsiCodeBlock body = method.getBody(); if (body == null) return false; PsiStatement[] statements = body.getStatements(); - if (statements.length != 1) return false; + if (statements.length == 0) return false; PsiStatement statement = statements[0]; if (PropertyUtil.isSimplePropertyGetter(method)) { if (statement instanceof PsiReturnStatement) { @@ -275,6 +275,7 @@ public class JavaFoldingBuilder extends CustomFoldingBuilder implements DumbAwar } } else if (PropertyUtil.isSimplePropertySetter(method)) { + if (statements.length > 1 && !(statements[1] instanceof PsiReturnStatement)) return false; if (statement instanceof PsiExpressionStatement) { PsiExpression expr = ((PsiExpressionStatement)statement).getExpression(); if (expr instanceof PsiAssignmentExpression) { @@ -651,7 +652,7 @@ public class JavaFoldingBuilder extends CustomFoldingBuilder implements DumbAwar return psiParameter.getName(); } }, ", "); - @NonNls final String lambdas = "{" + params + " =>"; + @NonNls final String lambdas = "#{" + params + " ->"; final int closureStart = expression.getTextRange().getStartOffset(); final int closureEnd = expression.getTextRange().getEndOffset(); diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java b/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java index 6a52ec171673..3a4b690af4e5 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java @@ -263,7 +263,7 @@ public class OverrideImplementUtil { } if (results.isEmpty()) { PsiMethod method1 = GenerateMembersUtil.substituteGenericMethod(method, substitutor, aClass); - + PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory(); PsiMethod result = (PsiMethod)factory.createClass("Dummy").add(method1); if (result instanceof PsiAnnotationMethod) { @@ -304,6 +304,20 @@ public class OverrideImplementUtil { } } + //method type params are not allowed when overriding from raw type + final PsiTypeParameterList list = result.getTypeParameterList(); + if (list != null) { + final PsiClass containingClass = method.getContainingClass(); + if (containingClass != null) { + for (PsiClassType classType : aClass.getSuperTypes()) { + if (InheritanceUtil.isInheritorOrSelf(PsiUtil.resolveClassInType(classType), containingClass, true) && classType.isRaw()) { + list.replace(JavaPsiFacade.getElementFactory(aClass.getProject()).createTypeParameterList()); + break; + } + } + } + } + annotateOnOverrideImplement(result, aClass, method, insertOverrideIfPossible); if (CodeStyleSettingsManager.getSettings(aClass.getProject()).REPEAT_SYNCHRONIZED && method.hasModifierProperty(PsiModifier.SYNCHRONIZED)) { @@ -523,6 +537,7 @@ public class OverrideImplementUtil { final List selectedElements = chooser.getSelectedElements(); if (selectedElements == null || selectedElements.isEmpty()) return; + LOG.assertTrue(aClass.isValid()); new WriteCommandAction(project, aClass.getContainingFile()) { protected void run(final Result result) throws Throwable { overrideOrImplementMethodsInRightPlace(editor, aClass, selectedElements, chooser.isCopyJavadoc(), chooser.isInsertOverrideAnnotation()); diff --git a/java/java-impl/src/com/intellij/codeInspection/MoveToPackageFix.java b/java/java-impl/src/com/intellij/codeInspection/MoveToPackageFix.java index ae00ea8e45e3..6fd29c5cacb5 100644 --- a/java/java-impl/src/com/intellij/codeInspection/MoveToPackageFix.java +++ b/java/java-impl/src/com/intellij/codeInspection/MoveToPackageFix.java @@ -86,7 +86,7 @@ public class MoveToPackageFix implements LocalQuickFix { } new MoveClassesOrPackagesProcessor( project, - new PsiElement[]{((PsiJavaFile) myFile).getClasses()[0]}, + ((PsiJavaFile) myFile).getClasses(), new SingleSourceRootMoveDestination(PackageWrapper.create(JavaDirectoryService.getInstance().getPackage(directory)), directory), false, false, null).run(); diff --git a/java/java-impl/src/com/intellij/codeInspection/ReplaceWithTernaryOperatorFix.java b/java/java-impl/src/com/intellij/codeInspection/ReplaceWithTernaryOperatorFix.java new file mode 100644 index 000000000000..d08ba72cc81f --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInspection/ReplaceWithTernaryOperatorFix.java @@ -0,0 +1,107 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.codeInspection; + +import com.intellij.codeInsight.CodeInsightUtilBase; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.ScrollType; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.*; +import com.intellij.psi.codeStyle.CodeStyleManager; +import com.intellij.psi.util.PsiTypesUtil; +import com.intellij.psi.util.PsiUtilBase; +import org.jetbrains.annotations.NotNull; + +/** + * @author Danila Ponomarenko + */ +public class ReplaceWithTernaryOperatorFix implements LocalQuickFix { + private final String myText; + + @NotNull + public String getName() { + return InspectionsBundle.message("inspection.replace.ternary.quickfix", myText); + } + + public ReplaceWithTernaryOperatorFix(@NotNull PsiExpression expressionToAssert) { + myText = expressionToAssert.getText(); + } + + @NotNull + @Override + public String getFamilyName() { + return InspectionsBundle.message("inspection.surround.if.family"); + } + + @Override + public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { + final PsiElement element = descriptor.getPsiElement(); + if (!(element instanceof PsiExpression)) { + return; + } + final PsiExpression expression = (PsiExpression)element; + + final PsiFile file = expression.getContainingFile(); + if (!CodeInsightUtilBase.prepareFileForWrite(file)) return; + final PsiConditionalExpression conditionalExpression = replaceWthConditionalExpression(project, myText + "!=null", expression, suggestDefaultValue(expression)); + + final PsiExpression elseExpression = conditionalExpression.getElseExpression(); + if (elseExpression != null) { + selectInEditor(elseExpression); + } + } + + private static void selectInEditor(@NotNull PsiElement element) { + final Editor editor = PsiUtilBase.findEditor(element); + if (editor == null) return; + + final TextRange expressionRange = element.getTextRange(); + editor.getCaretModel().moveToOffset(expressionRange.getStartOffset()); + editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); + editor.getSelectionModel().setSelection(expressionRange.getStartOffset(), expressionRange.getEndOffset()); + } + + @NotNull + private static PsiConditionalExpression replaceWthConditionalExpression(@NotNull Project project, + @NotNull String condition, + @NotNull PsiExpression expression, + @NotNull String defaultValue) { + final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); + + final PsiElement parent = expression.getParent(); + final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)factory.createExpressionFromText( + condition + " ? " + expression.getText() + " : " + defaultValue, + parent + ); + + final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); + return (PsiConditionalExpression)expression.replace( codeStyleManager.reformat(conditionalExpression)); + } + + public static boolean isAvailable(@NotNull PsiExpression qualifier, @NotNull PsiExpression expression) { + if (!qualifier.isValid() || qualifier.getText() == null) { + return false; + } + + return !(expression.getParent() instanceof PsiExpressionStatement); + } + + private static String suggestDefaultValue(@NotNull PsiExpression expression) { + PsiType type = expression.getType(); + return PsiTypesUtil.getDefaultValueOfType(type); + } +} diff --git a/java/java-impl/src/com/intellij/codeInspection/SurroundWithIfFix.java b/java/java-impl/src/com/intellij/codeInspection/SurroundWithIfFix.java index a6fb64d92833..3b651f71ee9a 100644 --- a/java/java-impl/src/com/intellij/codeInspection/SurroundWithIfFix.java +++ b/java/java-impl/src/com/intellij/codeInspection/SurroundWithIfFix.java @@ -81,8 +81,8 @@ public class SurroundWithIfFix implements LocalQuickFix { return InspectionsBundle.message("inspection.surround.if.family"); } - public boolean isAvailable(PsiExpression qualifier) { - if (!qualifier.isValid() || myText == null) { + public static boolean isAvailable(PsiExpression qualifier) { + if (!qualifier.isValid() || qualifier.getText() == null) { return false; } PsiStatement statement = PsiTreeUtil.getParentOfType(qualifier, PsiStatement.class); diff --git a/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java b/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java index 94e67278a58f..c6c6095a2a1b 100644 --- a/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java @@ -68,20 +68,28 @@ public class DataFlowInspection extends BaseLocalInspectionTool { return new OptionsPanel(); } + void test(@NotNull List l) { + final List list = null; + test(list); + } + @NotNull public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new JavaElementVisitor() { - @Override public void visitField(PsiField field) { + @Override + public void visitField(PsiField field) { if (isNullLiteralExpression(field.getInitializer()) && NullableNotNullManager.isNotNull(field)) { holder.registerProblem(field.getInitializer(), InspectionsBundle.message("dataflow.message.initializing.field.with.null")); } } - @Override public void visitMethod(PsiMethod method) { + @Override + public void visitMethod(PsiMethod method) { analyzeCodeBlock(method.getBody(), holder); } - @Override public void visitClassInitializer(PsiClassInitializer initializer) { + @Override + public void visitClassInitializer(PsiClassInitializer initializer) { analyzeCodeBlock(initializer.getBody(), holder); } }; @@ -109,35 +117,38 @@ public class DataFlowInspection extends BaseLocalInspectionTool { } @Nullable - private static LocalQuickFix[] createNPEFixes(PsiExpression qualifier) { - if (qualifier != null && - !(qualifier instanceof PsiMethodCallExpression) && - !(qualifier instanceof PsiLiteralExpression && ((PsiLiteralExpression)qualifier).getValue() == null)) { - try { - PsiBinaryExpression binary = (PsiBinaryExpression)JavaPsiFacade.getInstance(qualifier.getProject()).getElementFactory() - .createExpressionFromText("a != null", null); - binary.getLOperand().replace(qualifier); - List fixes = new SmartList(); + private static LocalQuickFix[] createNPEFixes(PsiExpression qualifier, PsiExpression expression) { + if (qualifier == null || expression == null) return null; + if (qualifier instanceof PsiMethodCallExpression) return null; + if (qualifier instanceof PsiLiteralExpression && ((PsiLiteralExpression)qualifier).getValue() == null) return null; - if (PsiUtil.getLanguageLevel(qualifier).isAtLeast(LanguageLevel.JDK_1_4)) { - fixes.add(new AddAssertStatementFix(binary)); - } - SurroundWithIfFix ifFix = new SurroundWithIfFix(qualifier); - if (ifFix.isAvailable(qualifier)) { - fixes.add(ifFix); - } - return fixes.toArray(new LocalQuickFix[fixes.size()]); + try { + final List fixes = new SmartList(); + + if (PsiUtil.getLanguageLevel(qualifier).isAtLeast(LanguageLevel.JDK_1_4)) { + final Project project = qualifier.getProject(); + final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory(); + final PsiBinaryExpression binary = (PsiBinaryExpression)elementFactory.createExpressionFromText("a != null", null); + binary.getLOperand().replace(qualifier); + fixes.add(new AddAssertStatementFix(binary)); } - catch (IncorrectOperationException e) { - LOG.error(e); - return null; + + if (SurroundWithIfFix.isAvailable(qualifier)) { + fixes.add(new SurroundWithIfFix(qualifier)); } + if (ReplaceWithTernaryOperatorFix.isAvailable(qualifier, expression)) { + fixes.add(new ReplaceWithTernaryOperatorFix(qualifier)); + } + return fixes.toArray(new LocalQuickFix[fixes.size()]); + } + catch (IncorrectOperationException e) { + LOG.error(e); + return null; } - return null; } private void createDescription(StandardDataFlowRunner runner, ProblemsHolder holder, StandardInstructionVisitor visitor) { - Pair,Set> constConditions = runner.getConstConditionalExpressions(); + Pair, Set> constConditions = runner.getConstConditionalExpressions(); Set trueSet = constConditions.getFirst(); Set falseSet = constConditions.getSecond(); Set npeSet = runner.getNPEInstructions(); @@ -164,7 +175,7 @@ public class DataFlowInspection extends BaseLocalInspectionTool { MethodCallInstruction mcInstruction = (MethodCallInstruction)instruction; if (mcInstruction.getCallExpression() instanceof PsiMethodCallExpression) { PsiMethodCallExpression callExpression = (PsiMethodCallExpression)mcInstruction.getCallExpression(); - LocalQuickFix[] fix = createNPEFixes(callExpression.getMethodExpression().getQualifierExpression()); + LocalQuickFix[] fix = createNPEFixes(callExpression.getMethodExpression().getQualifierExpression(), callExpression); holder.registerProblem(callExpression, InspectionsBundle.message("dataflow.message.npe.method.invocation"), @@ -176,13 +187,13 @@ public class DataFlowInspection extends BaseLocalInspectionTool { PsiElement elementToAssert = frInstruction.getElementToAssert(); PsiExpression expression = frInstruction.getExpression(); if (expression instanceof PsiArrayAccessExpression) { - LocalQuickFix[] fix = createNPEFixes((PsiExpression)elementToAssert); + LocalQuickFix[] fix = createNPEFixes((PsiExpression)elementToAssert, expression); holder.registerProblem(expression, InspectionsBundle.message("dataflow.message.npe.array.access"), fix); } else { - LocalQuickFix[] fix = createNPEFixes((PsiExpression)elementToAssert); + LocalQuickFix[] fix = createNPEFixes((PsiExpression)elementToAssert, expression); holder.registerProblem(elementToAssert, InspectionsBundle.message("dataflow.message.npe.field.access"), fix); @@ -207,7 +218,7 @@ public class DataFlowInspection extends BaseLocalInspectionTool { final LocalQuickFix localQuickFix = createSimplifyBooleanExpressionFix(psiAnchor, true); holder.registerProblem(psiAnchor, InspectionsBundle.message(underBinary ? "dataflow.message.constant.condition.whenriched" : "dataflow.message.constant.condition", Boolean.toString(true)), - localQuickFix==null?null:new LocalQuickFix[]{localQuickFix}); + localQuickFix == null ? null : new LocalQuickFix[]{localQuickFix}); } } else if (psiAnchor instanceof PsiSwitchLabelStatement) { @@ -228,7 +239,7 @@ public class DataFlowInspection extends BaseLocalInspectionTool { final LocalQuickFix localQuickFix = createSimplifyBooleanExpressionFix(psiAnchor, evaluatesToTrue); holder.registerProblem(psiAnchor, InspectionsBundle.message(underBinary ? "dataflow.message.constant.condition.whenriched" : "dataflow.message.constant.condition", Boolean.toString(evaluatesToTrue)), - localQuickFix == null ? null : new LocalQuickFix[]{localQuickFix}); + localQuickFix == null ? null : new LocalQuickFix[]{localQuickFix}); } } reportedAnchors.add(psiAnchor); @@ -241,15 +252,15 @@ public class DataFlowInspection extends BaseLocalInspectionTool { final String text = isNullLiteralExpression(expr) ? InspectionsBundle.message("dataflow.message.passing.null.argument") : InspectionsBundle.message("dataflow.message.passing.nullable.argument"); - LocalQuickFix[] fixes = createNPEFixes(expr); + LocalQuickFix[] fixes = createNPEFixes(expr, expr); holder.registerProblem(expr, text, fixes); } exprs = runner.getNullableAssignments(); for (PsiExpression expr : exprs) { final String text = isNullLiteralExpression(expr) - ? InspectionsBundle.message("dataflow.message.assigning.null") - : InspectionsBundle.message("dataflow.message.assigning.nullable"); + ? InspectionsBundle.message("dataflow.message.assigning.null") + : InspectionsBundle.message("dataflow.message.assigning.nullable"); holder.registerProblem(expr, text); } @@ -263,17 +274,16 @@ public class DataFlowInspection extends BaseLocalInspectionTool { final PsiExpression expr = statement.getReturnValue(); if (runner.isInNotNullMethod()) { final String text = isNullLiteralExpression(expr) - ? InspectionsBundle.message("dataflow.message.return.null.from.notnull") - : InspectionsBundle.message("dataflow.message.return.nullable.from.notnull"); + ? InspectionsBundle.message("dataflow.message.return.null.from.notnull") + : InspectionsBundle.message("dataflow.message.return.nullable.from.notnull"); holder.registerProblem(expr, text); } else if (AnnotationUtil.isAnnotatingApplicable(statement)) { final String text = isNullLiteralExpression(expr) - ? InspectionsBundle.message("dataflow.message.return.null.from.notnullable") - : InspectionsBundle.message("dataflow.message.return.nullable.from.notnullable"); + ? InspectionsBundle.message("dataflow.message.return.null.from.notnullable") + : InspectionsBundle.message("dataflow.message.return.nullable.from.notnullable"); final NullableNotNullManager manager = NullableNotNullManager.getInstance(expr.getProject()); - holder.registerProblem(expr, text, new AnnotateMethodFix(manager.getDefaultNullable(), ArrayUtil.toStringArray(manager.getNotNulls()))); - + holder.registerProblem(expr, text, new AnnotateMethodFix(manager.getDefaultNullable(), ArrayUtil.toStringArray(manager.getNotNulls()))); } } } @@ -343,7 +353,7 @@ public class DataFlowInspection extends BaseLocalInspectionTool { final PsiElement psiElement = descriptor.getPsiElement(); if (psiElement == null) return; final SimplifyBooleanExpressionFix fix = createIntention(psiElement, value); - if (fix==null) return; + if (fix == null) return; try { LOG.assertTrue(psiElement.isValid()); fix.invoke(project, null, psiElement.getContainingFile()); @@ -480,8 +490,8 @@ public class DataFlowInspection extends BaseLocalInspectionTool { private static class DataFlowInstructionVisitor extends StandardInstructionVisitor { protected void onAssigningToNotNullableVariable(AssignInstruction instruction, DataFlowRunner runner) { - ((StandardDataFlowRunner)runner).onAssigningToNotNullableVariable(instruction.getRExpression()); - } + ((StandardDataFlowRunner)runner).onAssigningToNotNullableVariable(instruction.getRExpression()); + } protected void onNullableReturn(CheckReturnValueInstruction instruction, DataFlowRunner runner) { ((StandardDataFlowRunner)runner).onNullableReturn(instruction.getReturn()); @@ -496,15 +506,15 @@ public class DataFlowInspection extends BaseLocalInspectionTool { } protected void onInstructionProducesNPE(MethodCallInstruction instruction, DataFlowRunner runner) { - ((StandardDataFlowRunner) runner).onInstructionProducesNPE(instruction); + ((StandardDataFlowRunner)runner).onInstructionProducesNPE(instruction); } protected void onUnboxingNullable(MethodCallInstruction instruction, DataFlowRunner runner) { - ((StandardDataFlowRunner) runner).onUnboxingNullable(instruction.getContext()); + ((StandardDataFlowRunner)runner).onUnboxingNullable(instruction.getContext()); } protected void onPassingNullParameter(DataFlowRunner runner, PsiExpression arg) { - ((StandardDataFlowRunner) runner).onPassingNullParameter(arg); // Parameters on stack are reverted. - } + ((StandardDataFlowRunner)runner).onPassingNullParameter(arg); // Parameters on stack are reverted. + } } } diff --git a/java/java-impl/src/com/intellij/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java b/java/java-impl/src/com/intellij/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java index d16b8e0b0bdf..f780b9d10f62 100644 --- a/java/java-impl/src/com/intellij/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java @@ -44,10 +44,10 @@ public class SuspiciousCollectionsMethodCallsInspection extends BaseLocalInspect } private static void setupPatternMethods(PsiManager manager, - GlobalSearchScope searchScope, - List patternMethods, - IntArrayList indices) { - final PsiClass collectionClass = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.util.Collection", searchScope); + GlobalSearchScope searchScope, + List patternMethods, + IntArrayList indices) { + final PsiClass collectionClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(CommonClassNames.JAVA_UTIL_COLLECTION, searchScope); PsiType[] javaLangObject = {PsiType.getJavaLangObject(manager, searchScope)}; MethodSignature removeSignature = MethodSignatureUtil.createMethodSignature("remove", javaLangObject, PsiTypeParameter.EMPTY_ARRAY, PsiSubstitutor.EMPTY); if (collectionClass != null) { @@ -58,7 +58,7 @@ public class SuspiciousCollectionsMethodCallsInspection extends BaseLocalInspect addMethod(contains, 0, patternMethods, indices); } - final PsiClass listClass = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.util.List", searchScope); + final PsiClass listClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(CommonClassNames.JAVA_UTIL_LIST, searchScope); if (listClass != null) { MethodSignature indexofSignature = MethodSignatureUtil.createMethodSignature("indexOf", javaLangObject, PsiTypeParameter.EMPTY_ARRAY, PsiSubstitutor.EMPTY); PsiMethod indexof = MethodSignatureUtil.findMethodBySignature(listClass, indexofSignature, false); @@ -68,7 +68,7 @@ public class SuspiciousCollectionsMethodCallsInspection extends BaseLocalInspect addMethod(lastindexof, 0, patternMethods, indices); } - final PsiClass mapClass = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.util.Map", searchScope); + final PsiClass mapClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(CommonClassNames.JAVA_UTIL_MAP, searchScope); if (mapClass != null) { PsiMethod remove = MethodSignatureUtil.findMethodBySignature(mapClass, removeSignature, false); addMethod(remove, 0, patternMethods, indices); @@ -96,11 +96,13 @@ public class SuspiciousCollectionsMethodCallsInspection extends BaseLocalInspect final List patternMethods = new ArrayList(); final IntArrayList indices = new IntArrayList(); return new JavaElementVisitor() { - @Override public void visitReferenceExpression(final PsiReferenceExpression expression) { + @Override + public void visitReferenceExpression(final PsiReferenceExpression expression) { visitExpression(expression); } - @Override public void visitMethodCallExpression(PsiMethodCallExpression methodCall) { + @Override + public void visitMethodCallExpression(PsiMethodCallExpression methodCall) { super.visitMethodCallExpression(methodCall); final String message = getSuspiciousMethodCallMessage(methodCall, REPORT_CONVERTIBLE_METHOD_CALLS, patternMethods, indices ); diff --git a/java/java-impl/src/com/intellij/lang/java/JavaDocumentationProvider.java b/java/java-impl/src/com/intellij/lang/java/JavaDocumentationProvider.java index 5529ed6c5332..ede0a8514603 100644 --- a/java/java-impl/src/com/intellij/lang/java/JavaDocumentationProvider.java +++ b/java/java-impl/src/com/intellij/lang/java/JavaDocumentationProvider.java @@ -72,25 +72,26 @@ public class JavaDocumentationProvider implements CodeDocumentationProvider, Ext @Override public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) { + String navigateInfo = null; if (element instanceof PsiClass) { - return generateClassInfo((PsiClass)element); + navigateInfo = generateClassInfo((PsiClass)element); } else if (element instanceof PsiMethod) { - return generateMethodInfo((PsiMethod)element, calcSubstitutor(originalElement)); + navigateInfo = generateMethodInfo((PsiMethod)element, calcSubstitutor(originalElement)); } else if (element instanceof PsiField) { - return generateFieldInfo((PsiField)element, calcSubstitutor(originalElement)); + navigateInfo = generateFieldInfo((PsiField)element, calcSubstitutor(originalElement)); } else if (element instanceof PsiVariable) { - return generateVariableInfo((PsiVariable)element); + navigateInfo = generateVariableInfo((PsiVariable)element); } else if (element instanceof PsiPackage) { - return generatePackageInfo((PsiPackage)element); + navigateInfo = generatePackageInfo((PsiPackage)element); } else if (element instanceof BeanPropertyElement) { - return generateMethodInfo(((BeanPropertyElement) element).getMethod(), PsiSubstitutor.EMPTY); + navigateInfo = generateMethodInfo(((BeanPropertyElement) element).getMethod(), PsiSubstitutor.EMPTY); } - return null; + return StringUtil.escapeXml(StringUtil.unescapeXml(navigateInfo)); } private static PsiSubstitutor calcSubstitutor(PsiElement originalElement) { diff --git a/java/java-impl/src/com/intellij/psi/filters/AnnotationParameterFilter.java b/java/java-impl/src/com/intellij/psi/filters/AnnotationParameterFilter.java deleted file mode 100644 index b7a6eab9f908..000000000000 --- a/java/java-impl/src/com/intellij/psi/filters/AnnotationParameterFilter.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.psi.filters; - -import com.intellij.psi.PsiAnnotation; -import com.intellij.psi.PsiAnnotationParameterList; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiNameValuePair; -import com.intellij.util.ReflectionCache; -import org.jetbrains.annotations.NonNls; - -/** - * @author peter - */ -public class AnnotationParameterFilter implements ElementFilter{ - private final Class myClass; - @NonNls private final String myParameterName; - private final String myAnnotationQualifiedName; - - - public AnnotationParameterFilter(final Class elementClass, - final String annotationQualifiedName, - @NonNls final String parameterName) { - myAnnotationQualifiedName = annotationQualifiedName; - myClass = elementClass; - myParameterName = parameterName; - } - - @Override - public boolean isAcceptable(Object element, PsiElement context) { - final PsiElement parent = ((PsiElement)element).getParent(); - if (parent instanceof PsiNameValuePair) { - final PsiNameValuePair pair = (PsiNameValuePair)parent; - final String name = pair.getName(); - if (myParameterName.equals(name) || name == null && "value".equals(myParameterName)) { - final PsiElement psiElement = pair.getParent(); - if (psiElement instanceof PsiAnnotationParameterList) { - final PsiElement grandParent = psiElement.getParent(); - if (grandParent instanceof PsiAnnotation) { - if (myAnnotationQualifiedName.equals(((PsiAnnotation)grandParent).getQualifiedName())) { - return true; - } - } - } - } - } - return false; - } - - @Override - public boolean isClassAcceptable(Class hintClass) { - return ReflectionCache.isAssignable(myClass, hintClass); - } -} diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/JavaReflectionCompletionConfidence.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/JavaReflectionCompletionConfidence.java index 6b77a6dcb752..35cbc362a0cb 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/JavaReflectionCompletionConfidence.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/JavaReflectionCompletionConfidence.java @@ -21,7 +21,6 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.ThreeState; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; /** * @author Konstantin Bulenkov @@ -35,12 +34,10 @@ public class JavaReflectionCompletionConfidence extends CompletionConfidence { @NotNull @Override - public ThreeState shouldSkipAutopopup(@Nullable PsiElement contextElement, @NotNull PsiFile psiFile, int offset) { - if (contextElement != null) { - final PsiElement literal = contextElement.getParent(); - if (literal != null && JavaReflectionReferenceContributor.PATTERN.accepts(literal)) { - return ThreeState.NO; - } + public ThreeState shouldSkipAutopopup(@NotNull PsiElement contextElement, @NotNull PsiFile psiFile, int offset) { + final PsiElement literal = contextElement.getParent(); + if (literal != null && JavaReflectionReferenceContributor.PATTERN.accepts(literal)) { + return ThreeState.NO; } return super.shouldSkipAutopopup(contextElement, psiFile, offset); } diff --git a/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java b/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java index 7f2f57965d61..d0212624665f 100644 --- a/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java @@ -318,10 +318,10 @@ public class CopyClassesHandler extends CopyHandlerDelegateBase { List files = new ArrayList(); for (final Map.Entry entry : fileToClasses.entrySet()) { final PsiFile psiFile = entry.getKey(); - if (psiFile instanceof PsiClassOwner) { + final PsiClass[] sources = entry.getValue(); + if (psiFile instanceof PsiClassOwner && sources != null) { final PsiFile createdFile = copy(psiFile, targetDirectory, copyClassName, map == null ? null : map.get(psiFile), choice); if (createdFile == null) return null; - final PsiClass[] sources = entry.getValue(); for (final PsiClass destination : ((PsiClassOwner)createdFile).getClasses()) { if (destination instanceof SyntheticElement) { continue; diff --git a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java index 3856c20bb935..c98e6b8da9d4 100644 --- a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java @@ -40,11 +40,11 @@ import com.intellij.refactoring.util.classMembers.MemberInfoStorage; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; import com.intellij.util.IncorrectOperationException; -import com.intellij.util.Processor;import com.intellij.util.containers.HashMap; +import com.intellij.util.Processor; +import com.intellij.util.containers.HashMap; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -63,39 +63,16 @@ public class InlineSuperClassRefactoringProcessor extends FixableUsagesRefactori myTargetClasses = targetClasses; MemberInfoStorage memberInfoStorage = new MemberInfoStorage(mySuperClass, new MemberInfo.Filter() { public boolean includeMember(PsiMember element) { - return true; + return !(element instanceof PsiClass) || PsiTreeUtil.isAncestor(mySuperClass, element, true); } }); List members = memberInfoStorage.getClassMemberInfos(mySuperClass); for (MemberInfo member : members) { member.setChecked(true); } - members = appendSuperRefs(members); myMemberInfos = members.toArray(new MemberInfo[members.size()]); } - private List appendSuperRefs(List members) { - if (!mySuperClass.isInterface()) { - PsiReferenceList extendsList = mySuperClass.getExtendsList(); - if (extendsList != null && extendsList.getReferenceElements().length > 0) { - PsiElement resolve = extendsList.getReferenceElements()[0].resolve(); - if (resolve instanceof PsiClass) { - members = new ArrayList(members); - - MemberInfo memberInfo = new MemberInfo((PsiMember)resolve, true, extendsList) { - { - overrides = false; - } - }; - - memberInfo.setChecked(true); - members.add(memberInfo); - } - } - } - return members; - } - @NotNull protected UsageViewDescriptor createUsageViewDescriptor(final UsageInfo[] usages) { return new InlineSuperClassUsageViewDescriptor(mySuperClass); diff --git a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceExtendsListUsageInfo.java b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceExtendsListUsageInfo.java index 686950aaba32..f9d28ac491b7 100644 --- a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceExtendsListUsageInfo.java +++ b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/usageInfo/ReplaceExtendsListUsageInfo.java @@ -21,22 +21,22 @@ package com.intellij.refactoring.inlineSuperClass.usageInfo; import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; import com.intellij.psi.PsiJavaCodeReferenceElement; +import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteExtendsClassUsageInfo; import com.intellij.refactoring.util.FixableUsageInfo; import com.intellij.util.IncorrectOperationException; public class ReplaceExtendsListUsageInfo extends FixableUsageInfo { + private final SafeDeleteExtendsClassUsageInfo mySafeDeleteUsageInfo; public ReplaceExtendsListUsageInfo(PsiJavaCodeReferenceElement element, final PsiClass superClass, final PsiClass targetClass) { super(element); - + mySafeDeleteUsageInfo = new SafeDeleteExtendsClassUsageInfo(element, superClass, targetClass); } public void fixUsage() throws IncorrectOperationException { - final PsiElement element = getElement(); - if (element != null) { - element.delete(); + if (mySafeDeleteUsageInfo.isSafeDelete()) { + mySafeDeleteUsageInfo.deleteElement(); } } } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceFieldPopup.java b/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceFieldPopup.java index ffd8645757fc..102b021103e3 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceFieldPopup.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/InplaceIntroduceFieldPopup.java @@ -111,7 +111,7 @@ public class InplaceIntroduceFieldPopup extends AbstractInplaceIntroduceFieldPop final boolean forStatic, @NotNull final PsiClass parentClass) { return IntroduceFieldDialog. - createGenerator(forStatic, localVariable, initializer, localVariable != null, null, parentClass). + createGenerator(forStatic, localVariable, initializer, localVariable != null, null, parentClass, parentClass.getProject()). getSuggestedNameInfo(defaultType); } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldDialog.java b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldDialog.java index 7d3ee870175c..0aaad5f3608f 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldDialog.java @@ -180,7 +180,7 @@ class IntroduceFieldDialog extends DialogWrapper { myNameSuggestionsManager = new NameSuggestionsManager(myTypeSelector, myNameField, createGenerator(myWillBeDeclaredStatic, myLocalVariable, myInitializerExpression, myIsInvokedOnDeclaration, myEnteredName, - myParentClass)); + myParentClass, myProject)); myNameSuggestionsManager.setLabelsFor(type, namePrompt); return panel; @@ -203,10 +203,12 @@ class IntroduceFieldDialog extends DialogWrapper { static NameSuggestionsGenerator createGenerator(final boolean willBeDeclaredStatic, final PsiLocalVariable localVariable, final PsiExpression initializerExpression, - final boolean isInvokedOnDeclaration, @Nullable final String enteredName, final PsiClass parentClass) { + final boolean isInvokedOnDeclaration, + @Nullable final String enteredName, + final PsiClass parentClass, + final Project project) { return new NameSuggestionsGenerator() { - private final JavaCodeStyleManager myCodeStyleManager = JavaCodeStyleManager.getInstance(localVariable != null ? localVariable.getProject() - : initializerExpression.getProject()); + private final JavaCodeStyleManager myCodeStyleManager = JavaCodeStyleManager.getInstance(project); public SuggestedNameInfo getSuggestedNameInfo(PsiType type) { VariableKind variableKind = willBeDeclaredStatic ? VariableKind.STATIC_FIELD : VariableKind.FIELD; diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java index cadb5c34b01a..38f3fe4e2e08 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java @@ -231,7 +231,7 @@ public class MoveClassesOrPackagesUtil { if (!moveDestination.equals(file.getContainingDirectory())) { LOG.assertTrue(file.getVirtualFile() != null, aClass); MoveFilesOrDirectoriesUtil.doMoveFile(file, moveDestination); - if (file instanceof PsiClassOwner && newPackage != null) { + if (file instanceof PsiClassOwner && newPackage != null && !JspPsiUtil.isInJspFile(file)) { ((PsiClassOwner)file).setPackageName(newPackage.getQualifiedName()); } } diff --git a/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationStatementProcessor.java b/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationStatementProcessor.java index b4700ee9a8d2..4b440d6a26dc 100644 --- a/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationStatementProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/typeMigration/TypeMigrationStatementProcessor.java @@ -59,9 +59,13 @@ class TypeMigrationStatementProcessor extends JavaRecursiveElementVisitor { final TypeView right = new TypeView(rExpression); final IElementType sign = expression.getOperationTokenType(); + final PsiType ltype = left.getType(); + final PsiType rtype = right.getType(); + if (ltype == null || rtype == null) return; + if (sign != JavaTokenType.EQ) { final IElementType binaryOperator = TypeConversionUtil.convertEQtoOperation(sign); - if (!TypeConversionUtil.isBinaryOperatorApplicable(binaryOperator, left.getType(), right.getType(), false)) { + if (!TypeConversionUtil.isBinaryOperatorApplicable(binaryOperator, ltype, rtype, false)) { if (left.isChanged()) { findConversionOrFail(expression, lExpression, left.getTypePair()); } @@ -77,11 +81,11 @@ class TypeMigrationStatementProcessor extends JavaRecursiveElementVisitor { break; case TypeInfection.LEFT_INFECTED: - myLabeler.migrateExpressionType(rExpression, left.getType(), myStatement, TypeConversionUtil.isAssignable(left.getType(), right.getType()), true); + myLabeler.migrateExpressionType(rExpression, ltype, myStatement, TypeConversionUtil.isAssignable(ltype, rtype), true); break; case TypeInfection.RIGHT_INFECTED: - myLabeler.migrateExpressionType(lExpression, right.getType(), myStatement, TypeConversionUtil.isAssignable(left.getType(), right.getType()), false); + myLabeler.migrateExpressionType(lExpression, rtype, myStatement, TypeConversionUtil.isAssignable(ltype, rtype), false); break; case TypeInfection.BOTH_INFECTED: diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java b/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java index addc8c2bc96c..cce007268945 100644 --- a/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java +++ b/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java @@ -36,11 +36,11 @@ import java.util.Set; */ public class JavaUsageTypeProvider implements UsageTypeProviderEx { public UsageType getUsageType(final PsiElement element) { - return getUsageType(element, null); + return getUsageType(element, UsageTarget.EMPTY_ARRAY); } @Override - public UsageType getUsageType(PsiElement element, @Nullable UsageTarget[] targets) { + public UsageType getUsageType(PsiElement element, @NotNull UsageTarget[] targets) { UsageType classUsageType = getClassUsageType(element, targets); if (classUsageType != null) return classUsageType; @@ -108,8 +108,10 @@ public class JavaUsageTypeProvider implements UsageTypeProviderEx { } private static boolean haveCommonSuperMethod(@NotNull PsiMethod m1, @NotNull PsiMethod m2) { - final Queue supers1Q = new ArrayDeque(); supers1Q.add(m1); - final Queue supers2Q = new ArrayDeque(); supers2Q.add(m2); + final Queue supers1Q = new ArrayDeque(); + supers1Q.add(m1); + final Queue supers2Q = new ArrayDeque(); + supers2Q.add(m2); Set supers1 = new THashSet(); Set supers2 = new THashSet(); while (true) { @@ -138,7 +140,7 @@ public class JavaUsageTypeProvider implements UsageTypeProviderEx { } }); } - if (me1 == null && me2==null) break; + if (me1 == null && me2 == null) break; } return false; /* @@ -154,9 +156,11 @@ public class JavaUsageTypeProvider implements UsageTypeProviderEx { } @Nullable - private static UsageType getClassUsageType(PsiElement element, @Nullable UsageTarget[] targets) { + private static UsageType getClassUsageType(@NotNull PsiElement element, @NotNull UsageTarget[] targets) { if (element.getParent() instanceof PsiAnnotation && - element == ((PsiAnnotation)element.getParent()).getNameReferenceElement()) return UsageType.ANNOTATION; + element == ((PsiAnnotation)element.getParent()).getNameReferenceElement()) { + return UsageType.ANNOTATION; + } if (PsiTreeUtil.getParentOfType(element, PsiImportStatement.class, false) != null) return UsageType.CLASS_IMPORT; PsiReferenceList referenceList = PsiTreeUtil.getParentOfType(element, PsiReferenceList.class); @@ -215,12 +219,15 @@ public class JavaUsageTypeProvider implements UsageTypeProviderEx { final PsiNewExpression psiNewExpression = PsiTreeUtil.getParentOfType(element, PsiNewExpression.class); if (psiNewExpression != null) { - final PsiJavaCodeReferenceElement classReference = psiNewExpression.getClassReference(); + final PsiJavaCodeReferenceElement classReference = psiNewExpression.getClassOrAnonymousClassReference(); if (classReference != null && PsiTreeUtil.isAncestor(classReference, element, false)) { + if (isAnonymousClassOf(psiNewExpression.getAnonymousClass(), targets)) { + return UsageType.CLASS_ANONYMOUS_NEW_OPERATOR; + } if (isInnerClassOf(classReference, targets)) { return UsageType.CLASS_INNER_NEW_OPERATOR; } - if (psiNewExpression.getArrayDimensions().length > 0) { + if (isNewArrayCreation(psiNewExpression)) { return UsageType.CLASS_NEW_ARRAY; } return UsageType.CLASS_NEW_OPERATOR; @@ -230,20 +237,33 @@ public class JavaUsageTypeProvider implements UsageTypeProviderEx { return null; } - private static boolean isInnerClassOf(PsiJavaCodeReferenceElement classReference, @Nullable UsageTarget[] targets) { - if (targets == null) { + private static boolean isNewArrayCreation(@NotNull PsiNewExpression expression){ + return expression.getArrayDimensions().length > 0 || expression.getArrayInitializer() != null; + } + + private static boolean isAnonymousClassOf(@Nullable PsiAnonymousClass anonymousClass, @NotNull UsageTarget[] targets) { + if (anonymousClass == null) { return false; } - PsiElement qualifier = classReference.getQualifier(); + + return qualifiesToTargetClasses(anonymousClass.getBaseClassReference(), targets); + } + + private static boolean isInnerClassOf(PsiJavaCodeReferenceElement classReference, @NotNull UsageTarget[] targets) { + final PsiElement qualifier = classReference.getQualifier(); if (qualifier instanceof PsiJavaCodeReferenceElement) { - for (UsageTarget target : targets) { - if (target instanceof PsiElementUsageTarget) { - PsiElement element = ((PsiElementUsageTarget)target).getElement(); - if (element instanceof PsiClass) { - String name = target.getName(); - if (Comparing.equal(((PsiJavaCodeReferenceElement)qualifier).getReferenceName(), name)) { - return true; - } + return qualifiesToTargetClasses((PsiJavaCodeReferenceElement)qualifier, targets); + } + return false; + } + + private static boolean qualifiesToTargetClasses(@NotNull PsiJavaCodeReferenceElement qualifier, @NotNull UsageTarget[] targets) { + for (UsageTarget target : targets) { + if (target instanceof PsiElementUsageTarget) { + PsiElement element = ((PsiElementUsageTarget)target).getElement(); + if (element instanceof PsiClass) { + if (Comparing.equal(qualifier.getReferenceName(), target.getName())) { + return true; } } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiSuperExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiSuperExpressionImpl.java index e6637553395f..d50bfcb1a21d 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiSuperExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiSuperExpressionImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,10 @@ import com.intellij.psi.impl.source.Constants; import com.intellij.psi.impl.source.tree.ChildRole; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.ChildRoleBase; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.util.PsiUtil; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class PsiSuperExpressionImpl extends ExpressionPsiElement implements PsiSuperExpression, Constants { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiSuperExpressionImpl"); @@ -38,17 +41,20 @@ public class PsiSuperExpressionImpl extends ExpressionPsiElement implements PsiS @Override public PsiType getType() { - PsiJavaCodeReferenceElement qualifier = getQualifier(); - if (qualifier != null){ + final PsiJavaCodeReferenceElement qualifier = getQualifier(); + if (qualifier != null) { final PsiElement aClass = qualifier.resolve(); - return aClass instanceof PsiClass ? getSuperType((PsiClass)aClass) : null; + if (!(aClass instanceof PsiClass)) return null; + return getSuperType((PsiClass)aClass, PsiUtil.isLanguageLevel8OrHigher(this)); } - for(PsiElement scope = getContext(); scope != null; scope = scope.getContext()){ - if (scope instanceof PsiClass){ - PsiClass aClass = (PsiClass)scope; - return getSuperType(aClass); + + for (PsiElement scope = getContext(); scope != null; scope = scope.getContext()) { + if (scope instanceof PsiClass) { + final PsiClass aClass = (PsiClass)scope; + return getSuperType(aClass, false); } - if (scope instanceof PsiExpressionList && scope.getParent() instanceof PsiAnonymousClass){ + if (scope instanceof PsiExpressionList && scope.getParent() instanceof PsiAnonymousClass) { + //noinspection AssignmentToForLoopParameter scope = scope.getParent(); } else if (scope instanceof JavaCodeFragment) { @@ -56,55 +62,56 @@ public class PsiSuperExpressionImpl extends ExpressionPsiElement implements PsiS if (fragmentSuperType != null) return fragmentSuperType; } } + return null; } - private PsiType getSuperType(PsiClass aClass) { + @Nullable + private PsiType getSuperType(PsiClass aClass, boolean checkImmediateSuperInterfaces) { + if (CommonClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName())) return null; + + final PsiClass containingClass = checkImmediateSuperInterfaces ? PsiTreeUtil.getParentOfType(this, PsiClass.class) : null; + if (containingClass != null) { + final PsiClassType[] superTypes; + if (containingClass.isInterface()) { + superTypes = containingClass.getExtendsListTypes(); + } + else if (containingClass instanceof PsiAnonymousClass) { + superTypes = new PsiClassType[]{((PsiAnonymousClass)containingClass).getBaseClassType()}; + } + else { + superTypes = containingClass.getImplementsListTypes(); + } + + for (PsiClassType superType : superTypes) { + final PsiClass superClass = superType.resolve(); + if (superClass != null && superClass.isInterface() && aClass.equals(superClass)) return superType; + } + } + if (aClass.isInterface()) { - JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject()); - return facade.getElementFactory().createType(facade.findClass("java.lang.Object", getResolveScope())); + return PsiType.getJavaLangObject(getManager(), getResolveScope()); } if (aClass instanceof PsiAnonymousClass) { final PsiClassType baseClassType = ((PsiAnonymousClass)aClass).getBaseClassType(); final PsiClass psiClass = baseClassType.resolve(); - if(psiClass != null && !psiClass.isInterface()){ - return baseClassType; - } - - return PsiType.getJavaLangObject(getManager(), getResolveScope()); + return psiClass != null && !psiClass.isInterface() ? baseClassType : PsiType.getJavaLangObject(getManager(), getResolveScope()); } - if ("java.lang.Object".equals(aClass.getQualifiedName())) return null; - PsiClassType[] superTypes = aClass.getExtendsListTypes(); - if (superTypes.length == 0) { - JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject()); - final PsiClass javaLangObject = facade.findClass("java.lang.Object", getResolveScope()); - if (javaLangObject != null) { - return facade.getElementFactory().createType(javaLangObject); - } - else { - return null; - } - } - - return superTypes[0]; + final PsiClassType[] superTypes = aClass.getExtendsListTypes(); + return superTypes.length == 0 ? PsiType.getJavaLangObject(getManager(), getResolveScope()) : superTypes[0]; } @Override public ASTNode findChildByRole(int role) { LOG.assertTrue(ChildRole.isUnique(role)); - switch(role){ + switch (role) { default: return null; case ChildRole.QUALIFIER: - if (getFirstChildNode().getElementType() == JAVA_CODE_REFERENCE){ - return getFirstChildNode(); - } - else{ - return null; - } + return getFirstChildNode().getElementType() == JAVA_CODE_REFERENCE ? getFirstChildNode() : null; case ChildRole.DOT: return findChildByType(DOT); diff --git a/java/java-psi-impl/src/messages/JavaErrorMessages.properties b/java/java-psi-impl/src/messages/JavaErrorMessages.properties index 3aae6ea3712b..51d626aaedbe 100644 --- a/java/java-psi-impl/src/messages/JavaErrorMessages.properties +++ b/java/java-psi-impl/src/messages/JavaErrorMessages.properties @@ -198,6 +198,7 @@ not.a.statement=Not a statement incompatible.types=Incompatible types. Found: ''{1}'', required: ''{0}'' valid.switch.selector.types=byte, char, short or int dot.expected.after.super.or.this='.' expected +unqualified.super.disallowed=Unqualified super reference is not allowed in extension method non.static.symbol.referenced.from.static.context=Non-static {0} ''{1}'' cannot be referenced from a static context private.symbol=''{0}'' has private access in ''{1}'' @@ -272,9 +273,6 @@ unclosed.char.literal=Unclosed character literal illegal.escape.character.in.string.literal=Illegal escape character in string literal floating.point.number.too.large=Floating point number too large floating.point.number.too.small=Floating point number too small -hex.FP.literals.not.supported=Hexadecimal floating point literals are only supported in JDK 5 or higher -binary.literals.not.supported=Binary literals are only supported in JDK 7 or higher -underscores.in.literals.not.supported=Underscores in literals are only supported in JDK 7 or higher import.statement.identifier.or.asterisk.expected.=Identifier or '*' expected @@ -348,8 +346,11 @@ feature.annotations=Annotations feature.static.imports=Static imports feature.for.each=For-each loops feature.varargs=Variable arity methods +feature.hex.fp.literals=Hexadecimal floating point literals feature.diamond.types=Diamond types feature.multi.catch=Multi-catches feature.try.with.resources=Try-with-resources +feature.binary.literals=Binary literals +feature.underscores.in.literals=Underscores in literals feature.extension.methods=Extension methods insufficient.language.level={0} are not supported at this language level diff --git a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInCastTypeParameters-out.java b/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInCastTypeParameters-out.java deleted file mode 100644 index 789404f0e818..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInCastTypeParameters-out.java +++ /dev/null @@ -1,7 +0,0 @@ - -public class Main { - - public static void main() { - x = (ProceedingJoinPoint> - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInCastTypeParameters.java b/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInCastTypeParameters.java deleted file mode 100644 index 8f5880237eb2..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInCastTypeParameters.java +++ /dev/null @@ -1,7 +0,0 @@ - -public class Main { - - public static void main() { - x = (ProceedingJoinPoint> - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInMethodParameters-out.java b/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInMethodParameters-out.java deleted file mode 100644 index 0fae50dd0fcc..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInMethodParameters-out.java +++ /dev/null @@ -1,5 +0,0 @@ -public class Xxx { - - - -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInMethodParameters.java b/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInMethodParameters.java deleted file mode 100644 index 3feb13009ce7..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsInMethodParameters.java +++ /dev/null @@ -1,5 +0,0 @@ -public class Xxx { - - - -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsWithRightContextInClassTypeParameters-out.java b/java/java-tests/testData/codeInsight/completion/keywords/ExtendsWithRightContextInClassTypeParameters-out.java deleted file mode 100644 index 26c81ac928a3..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsWithRightContextInClassTypeParameters-out.java +++ /dev/null @@ -1,3 +0,0 @@ -class Foo A> { - -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsWithRightContextInClassTypeParameters.java b/java/java-tests/testData/codeInsight/completion/keywords/ExtendsWithRightContextInClassTypeParameters.java deleted file mode 100644 index c90ad3278973..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/ExtendsWithRightContextInClassTypeParameters.java +++ /dev/null @@ -1,3 +0,0 @@ -class Foo A> { - -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally-out.java b/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally-out.java deleted file mode 100644 index 674fc428c5d9..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally-out.java +++ /dev/null @@ -1,12 +0,0 @@ - -public class Main { - - public static void main() { - try { - - } finally { - - } - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally.java b/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally.java deleted file mode 100644 index 81df57df6185..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally.java +++ /dev/null @@ -1,12 +0,0 @@ - -public class Main { - - public static void main() { - try { - - } final { - - } - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally1-out.java b/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally1-out.java deleted file mode 100644 index edb1b9a8e4f9..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally1-out.java +++ /dev/null @@ -1,12 +0,0 @@ - -public class Main { - - public static void main() { - try { - - } finally { - - } - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally1.java b/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally1.java deleted file mode 100644 index 1cd4a6d72590..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/ExtraBracketAfterFinally1.java +++ /dev/null @@ -1,10 +0,0 @@ - -public class Main { - - public static void main() { - try { - - } final - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/NullInIf-out.java b/java/java-tests/testData/codeInsight/completion/keywords/NullInIf-out.java deleted file mode 100644 index 9fd613410a95..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/NullInIf-out.java +++ /dev/null @@ -1,8 +0,0 @@ - -public class Main { - - public static void main() { - if (null) - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/NullInIf.java b/java/java-tests/testData/codeInsight/completion/keywords/NullInIf.java deleted file mode 100644 index 421cf16e078d..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/NullInIf.java +++ /dev/null @@ -1,8 +0,0 @@ - -public class Main { - - public static void main() { - if (nu) - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall.java b/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall.java deleted file mode 100644 index be803489e216..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall.java +++ /dev/null @@ -1,7 +0,0 @@ -class Null { - public static void main(String[] argv) { - StringBuffer buf = new StringBuffer(); - - buf.append(nu); - } -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall2.java b/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall2.java deleted file mode 100644 index 2233039cc872..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall2.java +++ /dev/null @@ -1,7 +0,0 @@ -class Null { - public static void main(String[] argv) { - StringBuffer buf = new StringBuffer(); - - buf.append(Null.nu); - } -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall2_After.java b/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall2_After.java deleted file mode 100644 index 2233039cc872..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall2_After.java +++ /dev/null @@ -1,7 +0,0 @@ -class Null { - public static void main(String[] argv) { - StringBuffer buf = new StringBuffer(); - - buf.append(Null.nu); - } -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall_After.java b/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall_After.java deleted file mode 100644 index 46fa66446e35..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/NullInMethodCall_After.java +++ /dev/null @@ -1,7 +0,0 @@ -class Null { - public static void main(String[] argv) { - StringBuffer buf = new StringBuffer(); - - buf.append(null); - } -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/NullInReturn-out.java b/java/java-tests/testData/codeInsight/completion/keywords/NullInReturn-out.java deleted file mode 100644 index 69f514804340..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/NullInReturn-out.java +++ /dev/null @@ -1,8 +0,0 @@ - -public class Main { - - public static Object main() { - return null - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/NullInReturn.java b/java/java-tests/testData/codeInsight/completion/keywords/NullInReturn.java deleted file mode 100644 index 503614beb68a..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/NullInReturn.java +++ /dev/null @@ -1,8 +0,0 @@ - -public class Main { - - public static Object main() { - return nu - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/TrueInVariableDeclaration-out.java b/java/java-tests/testData/codeInsight/completion/keywords/TrueInVariableDeclaration-out.java deleted file mode 100644 index c2f393fad7f6..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/TrueInVariableDeclaration-out.java +++ /dev/null @@ -1,8 +0,0 @@ - -public class Main { - - public static void main() { - boolean b = true - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/TrueInVariableDeclaration.java b/java/java-tests/testData/codeInsight/completion/keywords/TrueInVariableDeclaration.java deleted file mode 100644 index 13ee5ed52f3b..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/TrueInVariableDeclaration.java +++ /dev/null @@ -1,8 +0,0 @@ - -public class Main { - - public static void main() { - boolean b = tr - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/catch-1.java b/java/java-tests/testData/codeInsight/completion/keywords/catch-1.java deleted file mode 100644 index ba5ce5703432..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/catch-1.java +++ /dev/null @@ -1,8 +0,0 @@ -public class A{ - public void method(){ - try{ - String str = ""; - } - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/catchFinally.java b/java/java-tests/testData/codeInsight/completion/keywords/catchFinally.java new file mode 100644 index 000000000000..f724d93396b2 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/catchFinally.java @@ -0,0 +1,23 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(){ + try{ + String str = ""; + } + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/classScope-4.java b/java/java-tests/testData/codeInsight/completion/keywords/classScope-4.java deleted file mode 100644 index 0f6c3fdac00e..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/classScope-4.java +++ /dev/null @@ -1,3 +0,0 @@ -class A{ - -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/classScope-1.java b/java/java-tests/testData/codeInsight/completion/keywords/classScope1.java similarity index 100% rename from java/java-tests/testData/codeInsight/completion/keywords/classScope-1.java rename to java/java-tests/testData/codeInsight/completion/keywords/classScope1.java diff --git a/java/java-tests/testData/codeInsight/completion/keywords/classScope-2.java b/java/java-tests/testData/codeInsight/completion/keywords/classScope2.java similarity index 100% rename from java/java-tests/testData/codeInsight/completion/keywords/classScope-2.java rename to java/java-tests/testData/codeInsight/completion/keywords/classScope2.java diff --git a/java/java-tests/testData/codeInsight/completion/keywords/classScope-3.java b/java/java-tests/testData/codeInsight/completion/keywords/classScope3.java similarity index 100% rename from java/java-tests/testData/codeInsight/completion/keywords/classScope-3.java rename to java/java-tests/testData/codeInsight/completion/keywords/classScope3.java diff --git a/java/java-tests/testData/codeInsight/completion/keywords/classScope4.java b/java/java-tests/testData/codeInsight/completion/keywords/classScope4.java new file mode 100644 index 000000000000..24e7bfbbaea6 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/classScope4.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class A{ + +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/defaultInExtMethod.java b/java/java-tests/testData/codeInsight/completion/keywords/defaultInExtMethod.java new file mode 100644 index 000000000000..04b2a8a7035f --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/defaultInExtMethod.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface Foo { + String foo() def +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/defaultInExtMethod_after.java b/java/java-tests/testData/codeInsight/completion/keywords/defaultInExtMethod_after.java new file mode 100644 index 000000000000..22031018f7bc --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/defaultInExtMethod_after.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface Foo { + String foo() default +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-1.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-1.java deleted file mode 100644 index a928948d81c7..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-1.java +++ /dev/null @@ -1 +0,0 @@ -class x3 diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-10-result.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-10-result.java deleted file mode 100644 index 9a954ae8b337..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-10-result.java +++ /dev/null @@ -1,3 +0,0 @@ -class A{ - void >foo(){} -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-10.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-10.java deleted file mode 100644 index 68da0e944b46..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-10.java +++ /dev/null @@ -1,3 +0,0 @@ -class A{ - void >foo(){} -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-11-result.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-11-result.java deleted file mode 100644 index 87e818a076c7..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-11-result.java +++ /dev/null @@ -1,3 +0,0 @@ -class A{ - void >foo(){} -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-11.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-11.java deleted file mode 100644 index a8e5fc0e9df5..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-11.java +++ /dev/null @@ -1,3 +0,0 @@ -class A{ - void >foo(){} -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-12-result.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-12-result.java deleted file mode 100644 index 7127a5250e35..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-12-result.java +++ /dev/null @@ -1,5 +0,0 @@ -class A{ - { - Collection> - } -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-12.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-12.java deleted file mode 100644 index 2cc23359731c..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-12.java +++ /dev/null @@ -1,5 +0,0 @@ -class A{ - { - Collection> - } -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-2.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-2.java deleted file mode 100644 index 41399187fe37..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-2.java +++ /dev/null @@ -1,3 +0,0 @@ -class AAA{} - -class BBB extends diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-3.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-3.java deleted file mode 100644 index ce7fb1225cdc..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-3.java +++ /dev/null @@ -1,5 +0,0 @@ -class AAA{} - -interface CCC{} - -class BBB extends diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-4.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-4.java deleted file mode 100644 index ac0b51bfe351..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-4.java +++ /dev/null @@ -1,5 +0,0 @@ -class AAA{} - -interface CCC{} - -class BBB implements diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-5.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-5.java deleted file mode 100644 index ca5ec8e7c471..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-5.java +++ /dev/null @@ -1,3 +0,0 @@ -class AAA{} - -interface BBB extends diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-6.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-6.java deleted file mode 100644 index 4308b6710ec4..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-6.java +++ /dev/null @@ -1,3 +0,0 @@ -interface AAA{} - -interface BBB extends Runnable, diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-7-result.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-7-result.java deleted file mode 100644 index e768367d0430..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-7-result.java +++ /dev/null @@ -1,3 +0,0 @@ -class AAA{} - -class BBB extends AAA implements diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-7.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-7.java deleted file mode 100644 index 20b561ac6ce6..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-7.java +++ /dev/null @@ -1,3 +0,0 @@ -class AAA{} - -class BBB extends AAA i diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-8-result.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-8-result.java deleted file mode 100644 index 46fe4caea6dc..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-8-result.java +++ /dev/null @@ -1,4 +0,0 @@ -class AAA{} - -class BBB extends AAA implements { -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-8.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-8.java deleted file mode 100644 index 80dbed368970..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-8.java +++ /dev/null @@ -1,4 +0,0 @@ -class AAA{} - -class BBB extends AAA i { -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-9-result.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-9-result.java deleted file mode 100644 index 0a95953cba7d..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-9-result.java +++ /dev/null @@ -1 +0,0 @@ -interface AAAA extends \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends-9.java b/java/java-tests/testData/codeInsight/completion/keywords/extends-9.java deleted file mode 100644 index bd85a41f7537..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/extends-9.java +++ /dev/null @@ -1 +0,0 @@ -interface AAAA e \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends1.java b/java/java-tests/testData/codeInsight/completion/keywords/extends1.java new file mode 100644 index 000000000000..f3a5b845b5e5 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends1.java @@ -0,0 +1,16 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class x3 diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends10.java b/java/java-tests/testData/codeInsight/completion/keywords/extends10.java new file mode 100644 index 000000000000..3e32612445b9 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends10.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class A{ + void >foo(){} +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends10_after.java b/java/java-tests/testData/codeInsight/completion/keywords/extends10_after.java new file mode 100644 index 000000000000..ad63c3ba7526 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends10_after.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class A{ + void >foo(){} +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends11.java b/java/java-tests/testData/codeInsight/completion/keywords/extends11.java new file mode 100644 index 000000000000..a7cd5d64107c --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends11.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class A{ + void >foo(){} +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends11_after.java b/java/java-tests/testData/codeInsight/completion/keywords/extends11_after.java new file mode 100644 index 000000000000..201aa5f1bd61 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends11_after.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class A{ + void >foo(){} +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends12.java b/java/java-tests/testData/codeInsight/completion/keywords/extends12.java new file mode 100644 index 000000000000..880b0ebb132a --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends12.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class A{ + { + Collection> + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends12_after.java b/java/java-tests/testData/codeInsight/completion/keywords/extends12_after.java new file mode 100644 index 000000000000..7cf4bae3bd8c --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends12_after.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class A{ + { + Collection> + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends2.java b/java/java-tests/testData/codeInsight/completion/keywords/extends2.java new file mode 100644 index 000000000000..e00ac4c968aa --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends2.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AAA{} + +class BBB extends diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends3.java b/java/java-tests/testData/codeInsight/completion/keywords/extends3.java new file mode 100644 index 000000000000..00e012ba9122 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends3.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AAA{} + +interface CCC{} + +class BBB extends diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends4.java b/java/java-tests/testData/codeInsight/completion/keywords/extends4.java new file mode 100644 index 000000000000..0e7697bab3d7 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends4.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AAA{} + +interface CCC{} + +class BBB implements diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends5.java b/java/java-tests/testData/codeInsight/completion/keywords/extends5.java new file mode 100644 index 000000000000..cfec9d75e436 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends5.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AAA{} + +interface BBB extends diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends6.java b/java/java-tests/testData/codeInsight/completion/keywords/extends6.java new file mode 100644 index 000000000000..cfffdb15a989 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends6.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface AAA{} + +interface BBB extends Runnable, diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends7.java b/java/java-tests/testData/codeInsight/completion/keywords/extends7.java new file mode 100644 index 000000000000..3fb696c697b6 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends7.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AAA{} + +class BBB extends AAA i diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends7_after.java b/java/java-tests/testData/codeInsight/completion/keywords/extends7_after.java new file mode 100644 index 000000000000..3788648411f3 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends7_after.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AAA{} + +class BBB extends AAA implements diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends8.java b/java/java-tests/testData/codeInsight/completion/keywords/extends8.java new file mode 100644 index 000000000000..867fef89c73e --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends8.java @@ -0,0 +1,19 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AAA{} + +class BBB extends AAA i { +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends8_after.java b/java/java-tests/testData/codeInsight/completion/keywords/extends8_after.java new file mode 100644 index 000000000000..ea7a94e5fbd8 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends8_after.java @@ -0,0 +1,19 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AAA{} + +class BBB extends AAA implements { +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends9.java b/java/java-tests/testData/codeInsight/completion/keywords/extends9.java new file mode 100644 index 000000000000..37cf1f210eb9 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends9.java @@ -0,0 +1,16 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface AAAA e \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extends9_after.java b/java/java-tests/testData/codeInsight/completion/keywords/extends9_after.java new file mode 100644 index 000000000000..71f1777543af --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extends9_after.java @@ -0,0 +1,16 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface AAAA extends \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extendsInCastTypeParameters.java b/java/java-tests/testData/codeInsight/completion/keywords/extendsInCastTypeParameters.java new file mode 100644 index 000000000000..78fb3e9f244f --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extendsInCastTypeParameters.java @@ -0,0 +1,22 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static void main() { + x = (ProceedingJoinPoint> + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extendsInCastTypeParameters_after.java b/java/java-tests/testData/codeInsight/completion/keywords/extendsInCastTypeParameters_after.java new file mode 100644 index 000000000000..4a001127b4c4 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extendsInCastTypeParameters_after.java @@ -0,0 +1,22 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static void main() { + x = (ProceedingJoinPoint> + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extendsInMethodParameters.java b/java/java-tests/testData/codeInsight/completion/keywords/extendsInMethodParameters.java new file mode 100644 index 000000000000..6c467e38d4b4 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extendsInMethodParameters.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Xxx { + + + +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extendsInMethodParameters_after.java b/java/java-tests/testData/codeInsight/completion/keywords/extendsInMethodParameters_after.java new file mode 100644 index 000000000000..694dba7dfe6d --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extendsInMethodParameters_after.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Xxx { + + + +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extendsWithRightContextInClassTypeParameters.java b/java/java-tests/testData/codeInsight/completion/keywords/extendsWithRightContextInClassTypeParameters.java new file mode 100644 index 000000000000..30922b7a97ee --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extendsWithRightContextInClassTypeParameters.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Foo A> { + +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extendsWithRightContextInClassTypeParameters_after.java b/java/java-tests/testData/codeInsight/completion/keywords/extendsWithRightContextInClassTypeParameters_after.java new file mode 100644 index 000000000000..ef03219243ba --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extendsWithRightContextInClassTypeParameters_after.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Foo A> { + +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally1.java b/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally1.java new file mode 100644 index 000000000000..6a9f7502fbf0 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally1.java @@ -0,0 +1,27 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static void main() { + try { + + } final { + + } + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally1_after.java b/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally1_after.java new file mode 100644 index 000000000000..43512dd5bbd9 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally1_after.java @@ -0,0 +1,27 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static void main() { + try { + + } finally { + + } + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally2.java b/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally2.java new file mode 100644 index 000000000000..f1e428987e7c --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally2.java @@ -0,0 +1,25 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static void main() { + try { + + } final + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally2_after.java b/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally2_after.java new file mode 100644 index 000000000000..b99df3c0b2bb --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/extraBracketAfterFinally2_after.java @@ -0,0 +1,27 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static void main() { + try { + + } finally { + + } + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/fileScope-2.java b/java/java-tests/testData/codeInsight/completion/keywords/fileScope-2.java deleted file mode 100644 index faee6dcb6f1d..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/fileScope-2.java +++ /dev/null @@ -1,3 +0,0 @@ -package myPackage; - - diff --git a/java/java-tests/testData/codeInsight/completion/keywords/fileScope-1.java b/java/java-tests/testData/codeInsight/completion/keywords/fileScope1.java similarity index 100% rename from java/java-tests/testData/codeInsight/completion/keywords/fileScope-1.java rename to java/java-tests/testData/codeInsight/completion/keywords/fileScope1.java diff --git a/java/java-tests/testData/codeInsight/completion/keywords/fileScope2.java b/java/java-tests/testData/codeInsight/completion/keywords/fileScope2.java new file mode 100644 index 000000000000..e70c35c71309 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/fileScope2.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package myPackage; + + diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceOf1.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf1.java new file mode 100644 index 000000000000..c4ef6c7c1fc8 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf1.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(){ + boolean x = this i + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceOf1_after.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf1_after.java new file mode 100644 index 000000000000..344f74e8f6ed --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf1_after.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(){ + boolean x = this instanceof + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceOf2.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf2.java new file mode 100644 index 000000000000..a60c70ad806e --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf2.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(){ + boolean x = super + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceOf2_after.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf2_after.java new file mode 100644 index 000000000000..a60c70ad806e --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf2_after.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(){ + boolean x = super + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceOf3.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf3.java new file mode 100644 index 000000000000..fd6e661eb147 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf3.java @@ -0,0 +1,21 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(){ + String str = ""; + boolean x = str i + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceOf3_after.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf3_after.java new file mode 100644 index 000000000000..a2bac477b6b5 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/instanceOf3_after.java @@ -0,0 +1,21 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(){ + String str = ""; + boolean x = str instanceof + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-1-result.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceof-1-result.java deleted file mode 100644 index b86936886d2b..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-1-result.java +++ /dev/null @@ -1,5 +0,0 @@ -public class A{ - public void method(){ - boolean x = this instanceof - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-1.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceof-1.java deleted file mode 100644 index 0204407f2cb8..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-1.java +++ /dev/null @@ -1,5 +0,0 @@ -public class A{ - public void method(){ - boolean x = this i - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-2-result.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceof-2-result.java deleted file mode 100644 index b42010d5d531..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-2-result.java +++ /dev/null @@ -1,5 +0,0 @@ -public class A{ - public void method(){ - boolean x = super - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-2.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceof-2.java deleted file mode 100644 index b42010d5d531..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-2.java +++ /dev/null @@ -1,5 +0,0 @@ -public class A{ - public void method(){ - boolean x = super - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-3-result.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceof-3-result.java deleted file mode 100644 index 9bc7e1cd03ba..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-3-result.java +++ /dev/null @@ -1,6 +0,0 @@ -public class A{ - public void method(){ - String str = ""; - boolean x = str instanceof - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-3.java b/java/java-tests/testData/codeInsight/completion/keywords/instanceof-3.java deleted file mode 100644 index 4cb057454774..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/instanceof-3.java +++ /dev/null @@ -1,6 +0,0 @@ -public class A{ - public void method(){ - String str = ""; - boolean x = str i - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-1.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope-1.java deleted file mode 100644 index 640faaa19d11..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-1.java +++ /dev/null @@ -1,3 +0,0 @@ -public class A{ - public void method() {} -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-2.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope-2.java deleted file mode 100644 index 965cfb800962..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-2.java +++ /dev/null @@ -1,4 +0,0 @@ -public class A{ - public void method(){ - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-3.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope-3.java deleted file mode 100644 index dd99cb703a23..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-3.java +++ /dev/null @@ -1,5 +0,0 @@ -public class A{ - public void method(){ - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-4.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope-4.java deleted file mode 100644 index dd99cb703a23..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-4.java +++ /dev/null @@ -1,5 +0,0 @@ -public class A{ - public void method(){ - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-5-out.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope-5-out.java deleted file mode 100644 index 5ee694dc44d2..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-5-out.java +++ /dev/null @@ -1,5 +0,0 @@ -public class A{ - public void method(final String){ - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-5.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope-5.java deleted file mode 100644 index 93adde13ad59..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/methodScope-5.java +++ /dev/null @@ -1,5 +0,0 @@ -public class A{ - public void method(fi String){ - - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope1.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope1.java new file mode 100644 index 000000000000..1afc320d3736 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/methodScope1.java @@ -0,0 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method() {} +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope2.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope2.java new file mode 100644 index 000000000000..e6492ad07981 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/methodScope2.java @@ -0,0 +1,19 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(){ + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope3.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope3.java new file mode 100644 index 000000000000..b7dc464e92a8 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/methodScope3.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(){ + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope4.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope4.java new file mode 100644 index 000000000000..b7dc464e92a8 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/methodScope4.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(){ + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope5.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope5.java new file mode 100644 index 000000000000..685c9f478ad6 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/methodScope5.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(fi String){ + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/methodScope5_after.java b/java/java-tests/testData/codeInsight/completion/keywords/methodScope5_after.java new file mode 100644 index 000000000000..a270c75c12f5 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/methodScope5_after.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class A{ + public void method(final String){ + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/nullInIf.java b/java/java-tests/testData/codeInsight/completion/keywords/nullInIf.java new file mode 100644 index 000000000000..92a0dfedc82b --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/nullInIf.java @@ -0,0 +1,23 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static void main() { + if (nu) + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/nullInIf_after.java b/java/java-tests/testData/codeInsight/completion/keywords/nullInIf_after.java new file mode 100644 index 000000000000..b538755def32 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/nullInIf_after.java @@ -0,0 +1,23 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static void main() { + if (null) + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall.java b/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall.java new file mode 100644 index 000000000000..665f58fd6db3 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall.java @@ -0,0 +1,22 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Null { + public static void main(String[] argv) { + StringBuffer buf = new StringBuffer(); + + buf.append(nu); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall2.java b/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall2.java new file mode 100644 index 000000000000..bd1e40d515d5 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall2.java @@ -0,0 +1,22 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Null { + public static void main(String[] argv) { + StringBuffer buf = new StringBuffer(); + + buf.append(Null.nu); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall2_after.java b/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall2_after.java new file mode 100644 index 000000000000..bd1e40d515d5 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall2_after.java @@ -0,0 +1,22 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Null { + public static void main(String[] argv) { + StringBuffer buf = new StringBuffer(); + + buf.append(Null.nu); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall_after.java b/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall_after.java new file mode 100644 index 000000000000..53129988b57e --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/nullInMethodCall_after.java @@ -0,0 +1,22 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Null { + public static void main(String[] argv) { + StringBuffer buf = new StringBuffer(); + + buf.append(null); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/nullInReturn.java b/java/java-tests/testData/codeInsight/completion/keywords/nullInReturn.java new file mode 100644 index 000000000000..79fdea866365 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/nullInReturn.java @@ -0,0 +1,23 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static Object main() { + return nu + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/nullInReturn_after.java b/java/java-tests/testData/codeInsight/completion/keywords/nullInReturn_after.java new file mode 100644 index 000000000000..465b5e7a0067 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/nullInReturn_after.java @@ -0,0 +1,23 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static Object main() { + return null + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/super-1.java b/java/java-tests/testData/codeInsight/completion/keywords/super-1.java deleted file mode 100644 index 4450560b5f94..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/super-1.java +++ /dev/null @@ -1,7 +0,0 @@ -class B{ - class A{ - { - B. - } - } -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/super-2.java b/java/java-tests/testData/codeInsight/completion/keywords/super-2.java deleted file mode 100644 index 390b24a570d5..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/super-2.java +++ /dev/null @@ -1,5 +0,0 @@ -class A{ - { - String. - } -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/super1.java b/java/java-tests/testData/codeInsight/completion/keywords/super1.java new file mode 100644 index 000000000000..43c488caa888 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/super1.java @@ -0,0 +1,22 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class B{ + class A{ + { + B. + } + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/super2.java b/java/java-tests/testData/codeInsight/completion/keywords/super2.java new file mode 100644 index 000000000000..1780ecb2ef57 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/super2.java @@ -0,0 +1,20 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class A{ + { + String. + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/synchronized-1-result.java b/java/java-tests/testData/codeInsight/completion/keywords/synchronized-1-result.java deleted file mode 100644 index f9fb47045945..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/synchronized-1-result.java +++ /dev/null @@ -1,7 +0,0 @@ -class A { - void foo () { - new Runnable () { - public synchronized - }; - } -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/synchronized-1.java b/java/java-tests/testData/codeInsight/completion/keywords/synchronized-1.java deleted file mode 100644 index 692b71b7b8d1..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/synchronized-1.java +++ /dev/null @@ -1,7 +0,0 @@ -class A { - void foo () { - new Runnable () { - public synch - }; - } -} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/synchronized-2-result.java b/java/java-tests/testData/codeInsight/completion/keywords/synchronized-2-result.java deleted file mode 100644 index 859333d08a32..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/synchronized-2-result.java +++ /dev/null @@ -1,6 +0,0 @@ -class Test { - void foo() { - if (true) { - } else synchronized() - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/synchronized-2.java b/java/java-tests/testData/codeInsight/completion/keywords/synchronized-2.java deleted file mode 100644 index e2e5fe775cfb..000000000000 --- a/java/java-tests/testData/codeInsight/completion/keywords/synchronized-2.java +++ /dev/null @@ -1,6 +0,0 @@ -class Test { - void foo() { - if (true) { - } else syn - } -} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/synchronized1.java b/java/java-tests/testData/codeInsight/completion/keywords/synchronized1.java new file mode 100644 index 000000000000..e00064cce802 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/synchronized1.java @@ -0,0 +1,22 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class A { + void foo () { + new Runnable () { + public synch + }; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/synchronized1_after.java b/java/java-tests/testData/codeInsight/completion/keywords/synchronized1_after.java new file mode 100644 index 000000000000..519a52c66ec7 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/synchronized1_after.java @@ -0,0 +1,22 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class A { + void foo () { + new Runnable () { + public synchronized + }; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/synchronized2.java b/java/java-tests/testData/codeInsight/completion/keywords/synchronized2.java new file mode 100644 index 000000000000..d3ae6e142650 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/synchronized2.java @@ -0,0 +1,21 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Test { + void foo() { + if (true) { + } else syn + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/synchronized2_after.java b/java/java-tests/testData/codeInsight/completion/keywords/synchronized2_after.java new file mode 100644 index 000000000000..ef913dbd183e --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/synchronized2_after.java @@ -0,0 +1,21 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Test { + void foo() { + if (true) { + } else synchronized() + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/trueInVariableDeclaration.java b/java/java-tests/testData/codeInsight/completion/keywords/trueInVariableDeclaration.java new file mode 100644 index 000000000000..2a64ecfaf2c2 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/trueInVariableDeclaration.java @@ -0,0 +1,23 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static void main() { + boolean b = tr + + } +} diff --git a/java/java-tests/testData/codeInsight/completion/keywords/trueInVariableDeclaration_after.java b/java/java-tests/testData/codeInsight/completion/keywords/trueInVariableDeclaration_after.java new file mode 100644 index 000000000000..f202474e1e6f --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/trueInVariableDeclaration_after.java @@ -0,0 +1,23 @@ + +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class Main { + + public static void main() { + boolean b = true + + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Interface.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Interface.java index 1dc6b8c535c7..2d3c98953e1a 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Interface.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Interface.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ interface i implements Runnable {} interface ii {} @@ -9,12 +24,12 @@ interface is3 extends cs {} abstract class Exercis { public static void main() { - Object o = java.lang.this; - - new Runnable() { - public void run() { - Runnable.this.run(); /// - } - }; - } + Object o = java.lang.this; + + new Runnable() { + public void run() { + Runnable.this.run(); + } + }; + } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/NumericLiterals.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/NumericLiterals.java index d05587836cac..becdda581a2a 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/NumericLiterals.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/NumericLiterals.java @@ -1,3 +1,19 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /// assignment compatible types import java.io.*; import java.net.*; @@ -23,9 +39,9 @@ public class a { int i14 = 020000000000; int i15 = 0xf044332211; int octale = 017777777777; // negative - int bi1 = 0b0010; - int bi2 = 0B0010; - int bi3 = 1_2; + int bi1 = 0b0010; + int bi2 = 0B0010; + int bi3 = 1_2; long l1 = -9223372036854775809L; long l2 = 9223372036854775808L; @@ -39,20 +55,20 @@ public class a { long l10 = 0x8000000000000000L; long octalValue = 01777777777777777777600L; long octalValua = 01777777777777777777777L; - long bl1 = 0b0010l; - long bl2 = 0B0010L; - long bl3 = 10_24L; + long bl1 = 0b0010l; + long bl2 = 0B0010L; + long bl3 = 10_24L; float f1= 1e-46f; float f2 = 1e39f; float f3 = 0E1F; - float f4 = 0xabc.defP2f; - float bf1 = 3.141_592f; + float f4 = 0xabc.defP2f; + float bf1 = 3.141_592f; double dd1 = 1e-324; double dd2 = 1e309; double dd3 = 0E1; - double dd4 = 0x1.fffffffffffffP1023; + double dd4 = 0x1.fffffffffffffP1023; double d1 = 1.E; double d2 = 1.e; double d3 = 1.E+; @@ -64,6 +80,6 @@ public class a { double d9 = 1e-d; double d10 = 1e-F; double d11 = 1e-f; - double d12 = 3.141_592_653_589_793d; + double d12 = 3.141_592_653_589_793d; } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java index 909d08a364b9..2bb985bef33e 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java @@ -16,10 +16,31 @@ class C { interface I { + int i = 42; void m() default { } } + interface II extends I { + void m() default { + I.super.m(); + super.m(); + + System.out.println(I.super.i); + System.out.println(super.i); + } + + void ma(); + } + void test() { new I(){}.m(); + + new II() { + public void ma() { + I.super.m(); + II.super.m(); + II.super.ma(); + } + }.m(); } } \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterExpression.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterExpression.java new file mode 100644 index 000000000000..a3c59d28b3da --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterExpression.java @@ -0,0 +1,10 @@ +// "Replace with list access" "true" + +import java.lang.Math; +import java.util.List; + +class A { + void test(List lists) { + System.out.println(lists.get(Math.max(Math.abs(-2), 3))); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterIdexIsBoxedInteger.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterIdexIsBoxedInteger.java new file mode 100644 index 000000000000..e51dad27bce2 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterIdexIsBoxedInteger.java @@ -0,0 +1,10 @@ +// "Replace with list access" "true" + +import java.lang.Integer; +import java.util.ArrayList; + +class A { + void test(ArrayList list) { + System.out.println(list.get(new Integer(0))); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterListOfLists.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterListOfLists.java new file mode 100644 index 000000000000..88de14ce85d6 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterListOfLists.java @@ -0,0 +1,9 @@ +// "Replace with list access" "true" + +import java.util.List; + +class A { + void test(List lists) { + System.out.println(lists.get(0).get(0)); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterSetStatement.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterSetStatement.java new file mode 100644 index 000000000000..4996ab43fd67 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterSetStatement.java @@ -0,0 +1,9 @@ +// "Replace with list access" "true" + +import java.util.ArrayList; + +class A { + void test(ArrayList list) { + list.set(0, 5); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterSimple.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterSimple.java new file mode 100644 index 000000000000..b724741bac86 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/afterSimple.java @@ -0,0 +1,9 @@ +// "Replace with list access" "true" + +import java.util.ArrayList; + +class A { + void test(ArrayList list) { + System.out.println(list.get(0)); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeAssignmentInIfCondition.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeAssignmentInIfCondition.java new file mode 100644 index 000000000000..0ddfbf37d796 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeAssignmentInIfCondition.java @@ -0,0 +1,11 @@ +// "Replace with list access" "false" + +import java.util.ArrayList; + +class A { + void test(ArrayList list) { + if (list[0] = 5 == 5){ + + } + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeExpression.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeExpression.java new file mode 100644 index 000000000000..c24770fc7a26 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeExpression.java @@ -0,0 +1,10 @@ +// "Replace with list access" "true" + +import java.lang.Math; +import java.util.List; + +class A { + void test(List lists) { + System.out.println(lists[Math.max(Math.abs(-2),3)]); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeIdexIsBoxedInteger.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeIdexIsBoxedInteger.java new file mode 100644 index 000000000000..5aa0912933b9 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeIdexIsBoxedInteger.java @@ -0,0 +1,10 @@ +// "Replace with list access" "true" + +import java.lang.Integer; +import java.util.ArrayList; + +class A { + void test(ArrayList list) { + System.out.println(list[new Integer(0)]); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeIndexNotInteger.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeIndexNotInteger.java new file mode 100644 index 000000000000..3e357134a984 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeIndexNotInteger.java @@ -0,0 +1,10 @@ +// "Replace with list access" "false" + +import java.lang.Object; +import java.util.ArrayList; + +class A { + void test(ArrayList list) { + System.out.println(list[new Object(3)]); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeListOfLists.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeListOfLists.java new file mode 100644 index 000000000000..c657db61bce9 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeListOfLists.java @@ -0,0 +1,9 @@ +// "Replace with list access" "true" + +import java.util.List; + +class A { + void test(List lists) { + System.out.println(lists[0].get(0)); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeNotLIst.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeNotLIst.java new file mode 100644 index 000000000000..9b30417e9e57 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeNotLIst.java @@ -0,0 +1,6 @@ +// "Replace with list access" "false" +class A { + void test(Collection list) { + System.out.println(list[0]); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeSetStatement.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeSetStatement.java new file mode 100644 index 000000000000..fd502663b7f2 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeSetStatement.java @@ -0,0 +1,9 @@ +// "Replace with list access" "true" + +import java.util.ArrayList; + +class A { + void test(ArrayList list) { + list[0] = 5; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeSimple.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeSimple.java new file mode 100644 index 000000000000..4e96417cd6aa --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess/beforeSimple.java @@ -0,0 +1,9 @@ +// "Replace with list access" "true" + +import java.util.ArrayList; + +class A { + void test(ArrayList list) { + System.out.println(list[0]); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/afterMethodCall.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/afterMethodCall.java new file mode 100644 index 000000000000..76fbe9754ab3 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/afterMethodCall.java @@ -0,0 +1,10 @@ +// "Replace with 'list != null ?:'" "true" + +import org.jetbrains.annotations.NotNull; + +class A{ + void test(@NotNull List l) { + final List list = null; + test(list != null ? list : null); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/afterPrimitive.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/afterPrimitive.java new file mode 100644 index 000000000000..8547e4597503 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/afterPrimitive.java @@ -0,0 +1,10 @@ +// "Replace with 'integer != null ?:'" "true" + +import java.lang.Integer; + +class A{ + void test(){ + Integer integer = null; + int i = integer != null ? integer.intValue() : 0; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/afterSimple.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/afterSimple.java new file mode 100644 index 000000000000..aff3f94edb95 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/afterSimple.java @@ -0,0 +1,8 @@ +// "Replace with 'list != null ?:'" "true" + +class A{ + void test(){ + List list = null; + Object o = list != null ? list.get(0) : null; + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforeExpressionStatement.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforeExpressionStatement.java new file mode 100644 index 000000000000..b072c84b5674 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforeExpressionStatement.java @@ -0,0 +1,7 @@ +// "Replace with 'list != null ?:'" "false" +class A{ + void test(){ + List list = null; + list.get(0); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforeMethodCall.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforeMethodCall.java new file mode 100644 index 000000000000..9b5ec3919db9 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforeMethodCall.java @@ -0,0 +1,10 @@ +// "Replace with 'list != null ?:'" "true" + +import org.jetbrains.annotations.NotNull; + +class A{ + void test(@NotNull List l) { + final List list = null; + test(list); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforePrimitive.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforePrimitive.java new file mode 100644 index 000000000000..3af5be0ac1f5 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforePrimitive.java @@ -0,0 +1,10 @@ +// "Replace with 'integer != null ?:'" "true" + +import java.lang.Integer; + +class A{ + void test(){ + Integer integer = null; + int i = integer.intValue(); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforeSimple.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforeSimple.java new file mode 100644 index 000000000000..87652493e474 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator/beforeSimple.java @@ -0,0 +1,8 @@ +// "Replace with 'list != null ?:'" "true" + +class A{ + void test(){ + List list = null; + Object o = list.get(0); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/overrideImplement/afterRawSuper.java b/java/java-tests/testData/codeInsight/overrideImplement/afterRawSuper.java new file mode 100644 index 000000000000..95912a1bd1da --- /dev/null +++ b/java/java-tests/testData/codeInsight/overrideImplement/afterRawSuper.java @@ -0,0 +1,25 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface A { + void foo(); + } + + class B implements A + { + public void foo() { + //To change body of implemented methods use File | Settings | File Templates. + } + } diff --git a/java/java-tests/testData/codeInsight/overrideImplement/afterSubstituteBoundInMethodTypeParam.java b/java/java-tests/testData/codeInsight/overrideImplement/afterSubstituteBoundInMethodTypeParam.java new file mode 100644 index 000000000000..47816c480dca --- /dev/null +++ b/java/java-tests/testData/codeInsight/overrideImplement/afterSubstituteBoundInMethodTypeParam.java @@ -0,0 +1,26 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +abstract class A { + abstract void foo(S s); + } + + class B extends A{ // Implement methods + + @Override + void foo(S s) { + //To change body of implemented methods use File | Settings | File Templates. + } + } diff --git a/java/java-tests/testData/codeInsight/overrideImplement/beforeRawSuper.java b/java/java-tests/testData/codeInsight/overrideImplement/beforeRawSuper.java new file mode 100644 index 000000000000..aefe95c86643 --- /dev/null +++ b/java/java-tests/testData/codeInsight/overrideImplement/beforeRawSuper.java @@ -0,0 +1,24 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface A { + void foo(); + } + + class B implements A + { + + + } diff --git a/java/java-tests/testData/codeInsight/overrideImplement/beforeSubstituteBoundInMethodTypeParam.java b/java/java-tests/testData/codeInsight/overrideImplement/beforeSubstituteBoundInMethodTypeParam.java new file mode 100644 index 000000000000..0cccda1cebde --- /dev/null +++ b/java/java-tests/testData/codeInsight/overrideImplement/beforeSubstituteBoundInMethodTypeParam.java @@ -0,0 +1,22 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +abstract class A { + abstract void foo(S s); + } + + class B extends A{ // Implement methods + + } diff --git a/java/java-tests/testData/inspection/globalContext/Foo.java b/java/java-tests/testData/inspection/globalContext/Foo.java new file mode 100644 index 000000000000..4a2b44daf653 --- /dev/null +++ b/java/java-tests/testData/inspection/globalContext/Foo.java @@ -0,0 +1 @@ +public class Foo {} diff --git a/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/after/Super.java b/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/after/Super.java new file mode 100644 index 000000000000..f0c2064481b6 --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/after/Super.java @@ -0,0 +1,2 @@ +interface Int { +} diff --git a/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/after/Test.java b/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/after/Test.java new file mode 100644 index 000000000000..32dd1902afa5 --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/after/Test.java @@ -0,0 +1,2 @@ +interface Test extends Int { +} diff --git a/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/before/Super.java b/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/before/Super.java new file mode 100644 index 000000000000..35f223875043 --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/before/Super.java @@ -0,0 +1,4 @@ +interface Super extends Int { +} +interface Int { +} diff --git a/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/before/Test.java b/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/before/Test.java new file mode 100644 index 000000000000..2eeeb5d5fe8a --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineSuperClass/interfaceHierarchyWithSubstitution/before/Test.java @@ -0,0 +1,2 @@ +interface Test extends Super{ +} diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java index 3d0a160e8094..5a4b795126df 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java @@ -37,6 +37,8 @@ public class OverrideImplementTest extends LightCodeInsightTestCase { public void testWildcard() throws Exception { doTest(false); } public void testTypeParam() throws Exception { doTest(false); } public void testInterfaceAndAbstractClass() throws Exception { doTest(false); } + public void testRawSuper() throws Exception { doTest(false); } + public void testSubstituteBoundInMethodTypeParam() throws Exception { doTest(false); } public void testLongFinalParameterList() throws Exception { CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject()).clone(); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/KeywordCompletionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/completion/KeywordCompletionTest.java index 5885f56d7787..a8d77fc098e2 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/KeywordCompletionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/KeywordCompletionTest.java @@ -1,244 +1,110 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.codeInsight.completion; import com.intellij.JavaTestUtil; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; +import org.jetbrains.annotations.NonNls; /** - * Created by IntelliJ IDEA. - * User: ik - * Date: 20.02.2003 - * Time: 15:49:56 - * To change this template use Options | File Templates. + * @author ik + * @since 20.02.2003 */ public class KeywordCompletionTest extends LightCompletionTestCase { private static final String BASE_PATH = "/codeInsight/completion/keywords"; + private static final String[] FILE_SCOPE_KEYWORDS = new String[]{ + "package", "public", "private", "import", "final", "class", "interface", "abstract", "enum", null}; + private static final String[] CLASS_SCOPE_KEYWORDS = new String[]{ + "public", "private", "protected", "import", "final", "class", "interface", "abstract", "enum", null}; + private static final String[] CLASS_SCOPE_KEYWORDS_2 = new String[]{ + "package", "public", "private", "protected", "transient", "volatile", "static", "import", "final", "class", "interface", "abstract"}; + @Override protected String getTestDataPath() { return JavaTestUtil.getJavaTestDataPath(); } - private static final String[] ourPackageScopeKeywords = - new String[]{"package", "public", "private", "import", "final", "class", "interface", "abstract", "enum", null}; + public void testFileScope1() throws Exception { doTest(8, FILE_SCOPE_KEYWORDS); } + public void testFileScope2() throws Exception { doTest(7, CLASS_SCOPE_KEYWORDS); } + public void testClassScope1() throws Exception { doTest(5, CLASS_SCOPE_KEYWORDS); } + public void testClassScope2() throws Exception { doTest(4, CLASS_SCOPE_KEYWORDS); } + public void testClassScope3() throws Exception { doTest(0, CLASS_SCOPE_KEYWORDS); } + public void testClassScope4() throws Exception { doTest(10, CLASS_SCOPE_KEYWORDS_2); } + public void testAfterAnnotations() throws Exception { doTest(6, "public", "final", "class", "interface", "abstract", "enum", null); } + public void testExtends1() throws Exception { doTest(2, "extends", "implements", null); } + public void testExtends2() throws Exception { doTest(1, "extends", "implements", "AAA", "BBB", "instanceof"); } + public void testExtends3() throws Exception { doTest(2, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); } + public void testExtends4() throws Exception { doTest(2, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); } + public void testExtends5() throws Exception { doTest(1, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); } + public void testExtends6() throws Exception { doTest(1, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); } + public void testExtends7() throws Exception { doTest(false); } + public void testExtends8() throws Exception { doTest(false); } + public void testExtends9() throws Exception { doTest(false); } + public void testExtends10() throws Exception { doTest(false); } + public void testExtends11() throws Exception { doTest(false); } + public void testExtends12() throws Exception { doTest(false); } + public void testSynchronized1() throws Exception { doTest(false); } - public void testModifiersFileScope_1() throws Exception { - configureByFile(BASE_PATH + "/fileScope-1.java"); - testByCount(8, ourPackageScopeKeywords); - } - - private static final String[] ourClassScopeKeywords = - new String[]{"public", "private", "protected", "import", "final", "class", "interface", "abstract", "enum", null}; - - public void testModifiersFileScope_2() throws Exception { - configureByFile(BASE_PATH + "/fileScope-2.java"); - testByCount(7, ourClassScopeKeywords); - } - - public void testModifiersClassScope_1() throws Exception { - configureByFile(BASE_PATH + "/classScope-1.java"); - testByCount(5, ourClassScopeKeywords); - } - - public void testModifiersClassScope_2() throws Exception { - configureByFile(BASE_PATH + "/classScope-2.java"); - testByCount(4, ourClassScopeKeywords); - } - - public void testModifiersClassScope_3() throws Exception { - configureByFile(BASE_PATH + "/classScope-3.java"); - testByCount(0, ourClassScopeKeywords); - } - - public void testAfterAnnotations() throws Exception { - configureByFile(BASE_PATH + "/afterAnnotations.java"); - testByCount(6, "public", "final", "class", "interface", "abstract", "enum", null); - } - - public void testExtends_1() throws Exception { - configureByFile(BASE_PATH + "/extends-1.java"); - testByCount(2, "extends", "implements", null); - } - - public void testExtends_2() throws Exception { - configureByFile(BASE_PATH + "/extends-2.java"); - testByCount(1, "extends", "implements", "AAA", "BBB", "instanceof"); - } - - public void testExtends_3() throws Exception { - configureByFile(BASE_PATH + "/extends-3.java"); - testByCount(2, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); - } - - public void testExtends_4() throws Exception { - configureByFile(BASE_PATH + "/extends-4.java"); - testByCount(2, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); - } - - public void testExtends_5() throws Exception { - configureByFile(BASE_PATH + "/extends-5.java"); - testByCount(1, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); - } - - public void testExtends_6() throws Exception { - configureByFile(BASE_PATH + "/extends-6.java"); - testByCount(1, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); - } - - public void testExtends_7() throws Exception { - configureByFile(BASE_PATH + "/extends-7.java"); - checkResultByFile(BASE_PATH + "/extends-7-result.java"); - } - - public void testExtends_8() throws Exception { - configureByFile(BASE_PATH + "/extends-8.java"); - checkResultByFile(BASE_PATH + "/extends-8-result.java"); - } - - public void testExtends_9() throws Exception { - configureByFile(BASE_PATH + "/extends-9.java"); - checkResultByFile(BASE_PATH + "/extends-9-result.java"); - } - - public void testExtends_10() throws Exception { - configureByFile(BASE_PATH + "/extends-10.java"); - checkResultByFile(BASE_PATH + "/extends-10-result.java"); - } - - public void testExtends_11() throws Exception { - configureByFile(BASE_PATH + "/extends-11.java"); - checkResultByFile(BASE_PATH + "/extends-11-result.java"); - } - - public void testExtends_12() throws Exception { - configureByFile(BASE_PATH + "/extends-12.java"); - checkResultByFile(BASE_PATH + "/extends-12-result.java"); - } - - public void testSynchronized_1() throws Exception { - configureByFile(BASE_PATH + "/synchronized-1.java"); - checkResultByFile(BASE_PATH + "/synchronized-1-result.java"); - } - - public void testSynchronized_2() throws Exception { + public void testSynchronized2() throws Exception { CodeStyleSettingsManager.getSettings(getProject()).SPACE_BEFORE_SYNCHRONIZED_PARENTHESES = false; - configureByFile(BASE_PATH + "/synchronized-2.java"); - checkResultByFile(BASE_PATH + "/synchronized-2-result.java"); + doTest(false); } - public void testModifiersClassScope() throws Exception{ - configureByFile(BASE_PATH + "/classScope-4.java"); - testByCount(10, "package", "public", "private", "protected", "transient", "volatile", "static", "import", "final", "class", "interface", - "abstract"); - } + public void testMethodScope1() throws Exception { doTest(1, "throws"); } + public void testMethodScope2() throws Exception { doTest(1, "final", "public", "static", "volatile", "abstract"); } + public void testMethodScope3() throws Exception { doTest(1, "final", "public", "static", "volatile", "abstract", "throws", "instanceof"); } + public void testMethodScope4() throws Exception { doTest(6, "final", "try", "for", "while", "return", "throw"); } + public void testMethodScope5() throws Exception { doTest(false); } + public void testExtraBracketAfterFinally1() throws Exception { doTest(true); } + public void testExtraBracketAfterFinally2() throws Exception { doTest(true); } + public void testExtendsInCastTypeParameters() throws Exception { doTest(false); } + public void testExtendsWithRightContextInClassTypeParameters() throws Exception { doTest(false); } + public void testTrueInVariableDeclaration() throws Exception { doTest(false); } + public void testNullInIf() throws Exception { doTest(false); } + public void testNullInReturn() throws Exception { doTest(false); } + public void testExtendsInMethodParameters() throws Exception { doTest(false); } + public void testInstanceOf1() throws Exception { doTest(false); } + public void testInstanceOf2() throws Exception { doTest(false); } + public void testInstanceOf3() throws Exception { doTest(false); } + public void testCatchFinally() throws Exception { doTest(2, "catch", "finally"); } + public void testSuper1() throws Exception { doTest(1, "super"); } + public void testSuper2() throws Exception { doTest(0, "super"); } + public void testContinue() throws Exception { doTest(false); } + public void testThrowsOnSeparateLine() throws Exception { doTest(false); } + public void testDefaultInAnno() throws Exception { doTest(false); } + public void testDefaultInExtMethod() throws Exception { doTest(false); } + public void testNullInMethodCall() throws Exception { doTest(false); } + public void testNullInMethodCall2() throws Exception { doTest(false); } - public void testMethodThrows() throws Exception{ - configureByFile(BASE_PATH + "/methodScope-1.java"); - testByCount(1, "throws"); - } - - public void testModifiersInMethodScope_1() throws Exception{ - configureByFile(BASE_PATH + "/methodScope-2.java"); - testByCount(1, "final", "public", "static", "volatile", "abstract"); - } - - public void testModifiersInMethodScope_2() throws Exception{ - configureByFile(BASE_PATH + "/methodScope-3.java"); - testByCount(1, "final", "public", "static", "volatile", "abstract", "throws", "instanceof"); - } - - public void testModifiersInMethodScope_3() throws Exception{ - configureByFile(BASE_PATH + "/methodScope-4.java"); - testByCount(6, "final", "try", "for", "while", "return", "throw"); - } - - public void testModifiersInMethodScope_5() throws Exception{ - configureByFile(BASE_PATH + "/methodScope-5.java"); - checkResultByFile(BASE_PATH + "/methodScope-5-out.java"); - } - - public void testExtendsInCastTypeParameters() throws Throwable { doTest(); } - public void testExtendsWithRightContextInClassTypeParameters() throws Throwable { doTest(); } - - public void testExtraBracketAfterFinally() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); - selectItem(myItems[1]); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); - } - - public void testExtraBracketAfterFinally1() throws Throwable { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); - selectItem(myItems[1]); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); - } - - public void testTrueInVariableDeclaration() throws Throwable { doTest(); } - public void testNullInIf() throws Throwable { doTest(); } - public void testNullInReturn() throws Throwable { doTest(); } - - public void testExtendsInMethodParameters() throws Throwable { doTest(); } - - private void doTest() throws Exception { - configureByFile(BASE_PATH + "/" + getTestName(false) + ".java"); - checkResultByFile(BASE_PATH + "/" + getTestName(false) + "-out.java"); - } - - public void testInstanceOf_1() throws Exception{ - configureByFile(BASE_PATH + "/instanceof-1.java"); - checkResultByFile(BASE_PATH + "/instanceof-1-result.java"); - //testByCount(new String[]{"instanceof"}, 1); - } - - public void testInstanceOf_2() throws Exception{ - configureByFile(BASE_PATH + "/instanceof-2.java"); - checkResultByFile(BASE_PATH + "/instanceof-2-result.java"); - //testByCount(new String[]{"instanceof"}, 1); - } - - public void testInstanceOf_3() throws Exception{ - configureByFile(BASE_PATH + "/instanceof-3.java"); - checkResultByFile(BASE_PATH + "/instanceof-3-result.java"); - //testByCount(new String[]{"instanceof"}, 1); - } - - public void testCatchFinally() throws Exception{ - configureByFile(BASE_PATH + "/catch-1.java"); - testByCount(2, "catch", "finally"); - } - - public void testSuper1() throws Exception{ - configureByFile(BASE_PATH + "/super-1.java"); - testByCount(1, "super"); - } - - public void testSuper2() throws Exception{ - configureByFile(BASE_PATH + "/super-2.java"); - testByCount(0, "super"); - } - - public void testContinue() throws Exception{ - configureByFile(BASE_PATH + "/continue.java"); - checkResultByFile(BASE_PATH + "/continue_after.java"); - } - - public void testThrowsOnSeparateLine() throws Exception{ - configureByFile(BASE_PATH + "/throwsOnSeparateLine.java"); - checkResultByFile(BASE_PATH + "/throwsOnSeparateLine_after.java"); - } - - public void testDefaultInAnno() throws Exception{ - configureByFile(BASE_PATH + "/" + getTestName(true) + ".java"); - checkResultByFile(BASE_PATH + "/" + getTestName(true) + "_after.java"); - } - - public void testTryInExpression() throws Throwable { + public void testTryInExpression() throws Exception { configureByFile(BASE_PATH + "/" + getTestName(true) + ".java"); assertStringItems("toString", "this"); } - public void testNull() throws Exception{ - configureByFile(BASE_PATH + "/NullInMethodCall.java"); - checkResultByFile(BASE_PATH + "/NullInMethodCall_After.java"); - configureByFile(BASE_PATH + "/NullInMethodCall2.java"); - checkResultByFile(BASE_PATH + "/NullInMethodCall2_After.java"); + private void doTest(boolean select) throws Exception { + configureByFile(BASE_PATH + "/" + getTestName(true) + ".java"); + if (select) { + selectItem(myItems[1]); + } + checkResultByFile(BASE_PATH + "/" + getTestName(true) + "_after.java"); + } + + protected void doTest(int finalCount, @NonNls String... values) { + configureByFile(BASE_PATH + "/" + getTestName(true) + ".java"); + testByCount(finalCount, values); } } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/ReplaceWithListAccessTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/ReplaceWithListAccessTest.java new file mode 100644 index 000000000000..e5777643c4a8 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/ReplaceWithListAccessTest.java @@ -0,0 +1,29 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.codeInsight.daemon.quickFix; + +/** + * @author Danila Ponomarenko + */ +public class ReplaceWithListAccessTest extends LightQuickFixTestCase { + + public void test() throws Exception { doAllTests(); } + + @Override + protected String getBasePath() { + return "/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithListAccess"; + } +} diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/ReplaceWithTernaryOperatorTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/ReplaceWithTernaryOperatorTest.java new file mode 100644 index 000000000000..6419088e9583 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/ReplaceWithTernaryOperatorTest.java @@ -0,0 +1,41 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * User: anna + * Date: 21-Mar-2008 + */ +package com.intellij.codeInsight.daemon.quickFix; + +import com.intellij.codeInspection.LocalInspectionTool; +import com.intellij.codeInspection.dataFlow.DataFlowInspection; +import com.intellij.codeInspection.nullable.NullableStuffInspection; + +public class ReplaceWithTernaryOperatorTest extends LightQuickFixTestCase { + @Override + protected LocalInspectionTool[] configureLocalInspectionTools() { + return new LocalInspectionTool[]{new DataFlowInspection(), new NullableStuffInspection()}; + } + + public void test() throws Exception { + doAllTests(); + } + + @Override + protected String getBasePath() { + return "/codeInsight/daemonCodeAnalyzer/quickFix/replaceWithTernaryOperator"; + } +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy index 20830a89f107..f993262b32ac 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy @@ -168,6 +168,27 @@ class Test { assertNotNull closureFolds assertEquals(2, closureFolds.size()) } + + public void "test builder style setter"() { + myFoldingSettings.COLLAPSE_ACCESSORS = true + def text = """\ +class Foo { + private String bar; + + public Foo setBar(String bar) { + this.bar = bar; + return this; + } +} +""" + + configure text + def foldingModel = myFixture.editor.foldingModel as FoldingModelImpl + int indexOfBar = text.indexOf("this.bar") + def accessorStartFold = foldingModel.getCollapsedRegionAtOffset(indexOfBar) + assertNotNull accessorStartFold + assertFalse accessorStartFold.expanded + } public void "test closure folding doesn't expand when editing inside"() { def text = """\ diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/GlobalInspectionContextTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/GlobalInspectionContextTest.java new file mode 100644 index 000000000000..809f49672384 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/codeInspection/GlobalInspectionContextTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.codeInspection; + +import com.intellij.JavaTestUtil; +import com.intellij.analysis.AnalysisScope; +import com.intellij.codeInsight.CodeInsightTestCase; +import com.intellij.codeInspection.ex.*; +import com.intellij.codeInspection.visibility.VisibilityInspection; + +/** + * @author Dmitry Avdeev + * Date: 5/24/12 + */ +public class GlobalInspectionContextTest extends CodeInsightTestCase { + + public void testProblemDuplication() throws Exception { + String shortName = new VisibilityInspection().getShortName(); + InspectionProfileImpl profile = new InspectionProfileImpl("Foo"); + profile.disableAllTools(); + profile.enableTool(shortName); + + GlobalInspectionContextImpl context = ((InspectionManagerEx)InspectionManager.getInstance(getProject())).createNewGlobalContext(false); + context.setExternalProfile(profile); + configureByFile("Foo.java"); + + AnalysisScope scope = new AnalysisScope(getFile()); + context.doInspections(scope, InspectionManager.getInstance(getProject())); + + Tools tools = context.getTools().get(shortName); + GlobalInspectionToolWrapper tool = (GlobalInspectionToolWrapper)tools.getTool(); + assertEquals(1, tool.getProblemDescriptors().size()); + + context.doInspections(scope, InspectionManager.getInstance(getProject())); + tools = context.getTools().get(shortName); + tool = (GlobalInspectionToolWrapper)tools.getTool(); + assertEquals(1, tool.getProblemDescriptors().size()); + } + + @Override + public void setUp() throws Exception { + super.setUp(); + InspectionProfileImpl.INIT_INSPECTIONS = true; + } + + @Override + public void tearDown() throws Exception { + InspectionProfileImpl.INIT_INSPECTIONS = false; + super.tearDown(); + } + + @Override + protected String getTestDataPath() { + return JavaTestUtil.getJavaTestDataPath() + "/inspection/globalContext/"; + } +} diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java index bb012a5b2665..94c1e9100a8c 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java @@ -28,7 +28,6 @@ import org.jdom.JDOMException; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.Map; import static com.intellij.testFramework.PlatformTestUtil.assertElementsEqual; @@ -221,8 +220,6 @@ public class InspectionProfileTest extends LightIdeaTestCase { GlobalInspectionContextImpl context = ((InspectionManagerEx)InspectionManager.getInstance(getProject())).createNewGlobalContext(false); context.setExternalProfile(profile); context.initializeTools(new ArrayList(), new ArrayList(), new ArrayList()); - Map tools = context.getTools(); - assertEquals(1, tools.size()); } private static LocalInspectionToolWrapper createTool(String s) { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/InlineSuperClassTest.java b/java/java-tests/testSrc/com/intellij/refactoring/InlineSuperClassTest.java index 3370d5863e06..fb7d2a75a9a7 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/InlineSuperClassTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/InlineSuperClassTest.java @@ -173,6 +173,10 @@ public class InlineSuperClassTest extends MultiFileTestCase { doTest(); } + public void testInterfaceHierarchyWithSubstitution() throws Exception { + doTest(); + } + private void doTestMultipleSubclasses() throws Exception { doTest(new PerformAction() { @Override diff --git a/java/java-tests/testSrc/com/intellij/refactoring/InplaceRenameInvariantTest.groovy b/java/java-tests/testSrc/com/intellij/refactoring/InplaceRenameInvariantTest.groovy new file mode 100644 index 000000000000..17c4694f3b9e --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/refactoring/InplaceRenameInvariantTest.groovy @@ -0,0 +1,129 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.refactoring + +import com.intellij.codeInsight.TargetElementUtilBase +import com.intellij.codeInsight.template.TemplateManager +import com.intellij.codeInsight.template.impl.TemplateManagerImpl +import com.intellij.codeInsight.template.impl.TemplateState +import com.intellij.psi.PsiElement +import com.intellij.refactoring.rename.inplace.MemberInplaceRenameHandler +import com.intellij.testFramework.LightCodeInsightTestCase + +/** + * User: anna + */ +class InplaceRenameInvariantTest extends LightCodeInsightTestCase { + public void "test start caret position"() { + def text = """\ + class Test { + } + } + """ + + doTestPositionInvariance(text, false) + } + + public void "test middle caret position"() { + def text = """\ + class Test { + } + } + """ + + doTestPositionInvariance(text, false) + } + + public void "test end caret position"() { + def text = """\ + class Test { + } + } + """ + + doTestPositionInvariance(text, false) + } + + + public void "test start caret position preselect"() { + def text = """\ + class Test { + } + } + """ + + doTestPositionInvariance(text, true) + } + + public void "test middle caret position preselect"() { + def text = """\ + class Test { + } + } + """ + + doTestPositionInvariance(text, true) + } + + public void "test end caret position preselect"() { + def text = """\ + class Test { + } + } + """ + + doTestPositionInvariance(text, true) + } + + private doTestPositionInvariance(String text, final boolean preselect) { + configure text + TemplateManagerImpl templateManager = (TemplateManagerImpl)TemplateManager.getInstance(project) + def oldPreselectSetting = myEditor.settings.preselectRename + try { + templateManager.templateTesting = true + myEditor.settings.preselectRename = preselect; + int offset = myEditor.caretModel.offset + final PsiElement element = TargetElementUtilBase.findTargetElement(myEditor, TargetElementUtilBase.getInstance().getAllAccepted()) + + assertNotNull(element) + + MemberInplaceRenameHandler handler = new MemberInplaceRenameHandler() + + + handler.doRename(element, editor, null); + + assertEquals(offset, myEditor.caretModel.offset) + } + finally { + myEditor.settings.preselectRename = oldPreselectSetting + + try { + TemplateState state = TemplateManagerImpl.getTemplateState(editor) + + assertNotNull(state) + + state.gotoEnd(false) + } + finally { + templateManager.templateTesting = false + } + } + } + + private def configure(String text) { + configureFromFileText("a.java", text) + } +} \ No newline at end of file diff --git a/java/openapi/src/com/intellij/codeInsight/NullableNotNullManager.java b/java/openapi/src/com/intellij/codeInsight/NullableNotNullManager.java index ab1324b1f0a2..85c3adb9009d 100644 --- a/java/openapi/src/com/intellij/codeInsight/NullableNotNullManager.java +++ b/java/openapi/src/com/intellij/codeInsight/NullableNotNullManager.java @@ -65,6 +65,7 @@ public class NullableNotNullManager implements PersistentStateComponent private static void addAllIfNotPresent(Collection collection, String... annotations) { for (String annotation : annotations) { + LOG.assertTrue(annotation != null); if (!collection.contains(annotation)) { collection.add(annotation); } diff --git a/java/openapi/src/com/intellij/patterns/PsiJavaPatterns.java b/java/openapi/src/com/intellij/patterns/PsiJavaPatterns.java index 2da9c756a728..3de211add605 100644 --- a/java/openapi/src/com/intellij/patterns/PsiJavaPatterns.java +++ b/java/openapi/src/com/intellij/patterns/PsiJavaPatterns.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ public class PsiJavaPatterns extends StandardPatterns{ return psiLiteral(null); } - public static PsiJavaElementPattern.Capture psiLiteral(final ElementPattern value) { + public static PsiJavaElementPattern.Capture psiLiteral(@Nullable final ElementPattern value) { return new PsiJavaElementPattern.Capture(new InitialPatternConditionPlus(PsiLiteral.class) { public boolean accepts(@Nullable final Object o, final ProcessingContext context) { return o instanceof PsiLiteral && (value == null || value.accepts(((PsiLiteral)o).getValue(), context)); @@ -100,12 +100,10 @@ public class PsiJavaPatterns extends StandardPatterns{ }); } - - public static PsiJavaElementPattern.Capture literalExpression(final ElementPattern value) { + public static PsiJavaElementPattern.Capture literalExpression(@Nullable final ElementPattern value) { return new PsiJavaElementPattern.Capture(new InitialPatternConditionPlus(PsiLiteralExpression.class) { public boolean accepts(@Nullable final Object o, final ProcessingContext context) { - return o instanceof PsiLiteralExpression - && (value == null || value.accepts(((PsiLiteralExpression)o).getValue(), context)); + return o instanceof PsiLiteralExpression && (value == null || value.accepts(((PsiLiteralExpression)o).getValue(), context)); } @Override diff --git a/java/testFramework/src/com/intellij/testFramework/IdeaTestUtil.java b/java/testFramework/src/com/intellij/testFramework/IdeaTestUtil.java index 2ae92ce833ac..98d260e93b6e 100644 --- a/java/testFramework/src/com/intellij/testFramework/IdeaTestUtil.java +++ b/java/testFramework/src/com/intellij/testFramework/IdeaTestUtil.java @@ -32,23 +32,22 @@ public class IdeaTestUtil extends PlatformTestUtil { public static void withLevel(final Module module, final LanguageLevel level, final Runnable r) { final LanguageLevelProjectExtension projectExt = LanguageLevelProjectExtension.getInstance(module.getProject()); - final LanguageLevelModuleExtension moduleExt = LanguageLevelModuleExtension.getInstance(module); final LanguageLevel projectLevel = projectExt.getLanguageLevel(); - final LanguageLevel moduleLevel = moduleExt.getLanguageLevel(); + final LanguageLevel moduleLevel = LanguageLevelModuleExtension.getInstance(module).getLanguageLevel(); try { projectExt.setLanguageLevel(level); - setModuleLanguageLevel(level, moduleExt); + setModuleLanguageLevel(module, level); r.run(); } finally { - setModuleLanguageLevel(moduleLevel, moduleExt); + setModuleLanguageLevel(module, moduleLevel); projectExt.setLanguageLevel(projectLevel); } } - private static void setModuleLanguageLevel(final LanguageLevel level, final LanguageLevelModuleExtension moduleExt) { - final LanguageLevelModuleExtension modifiable = (LanguageLevelModuleExtension)moduleExt.getModifiableModel(true); + public static void setModuleLanguageLevel(Module module, final LanguageLevel level) { + final LanguageLevelModuleExtension modifiable = (LanguageLevelModuleExtension)LanguageLevelModuleExtension.getInstance(module).getModifiableModel(true); modifiable.setLanguageLevel(level); modifiable.commit(); } diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java index 4f15cf5b7152..d3b59be07ecb 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java @@ -38,8 +38,7 @@ import org.jetbrains.jps.incremental.storage.BuildDataManager; import org.jetbrains.jps.incremental.storage.SourceToFormMapping; import org.jetbrains.jps.javac.*; -import javax.tools.Diagnostic; -import javax.tools.JavaFileObject; +import javax.tools.*; import java.io.*; import java.net.MalformedURLException; import java.net.ServerSocket; @@ -60,8 +59,14 @@ public class JavaBuilder extends ModuleLevelBuilder { private static final String FORM_EXTENSION = ".form"; public static final boolean USE_EMBEDDED_JAVAC = System.getProperty(GlobalOptions.USE_EXTERNAL_JAVAC_OPTION) == null; private static final Key JAVA_COMPILER_VERSION_KEY = Key.create("_java_compiler_version_"); + private static final Set FILTERED_OPTIONS = new HashSet(Arrays.asList( + "-target" + )); + private static final Set FILTERED_SINGLE_OPTIONS = new HashSet(Arrays.asList( + "-g", "-deprecation", "-nowarn", "-verbose" + )); - public static final FileFilter JAVA_SOURCES_FILTER = new FileFilter() { + private static final FileFilter JAVA_SOURCES_FILTER = new FileFilter() { public boolean accept(File file) { return file.getPath().endsWith(JAVA_EXTENSION); } @@ -282,8 +287,12 @@ public class JavaBuilder extends ModuleLevelBuilder { final String chunkName = getChunkPresentableName(chunk); context.processMessage(new ProgressMessage("Compiling java [" + chunkName + "]")); - final boolean compiledOk = - files.isEmpty() || compileJava(chunk, files, classpath, platformCp, sourcePath, outs, context, diagnosticSink, outputSink); + final int filesCount = files.size(); + boolean compiledOk = true; + if (filesCount > 0) { + LOG.info("Compiling " + filesCount + " java files; module: " + chunkName); + compiledOk = compileJava(chunk, files, classpath, platformCp, sourcePath, outs, context, diagnosticSink, outputSink); + } context.checkCanceled(); @@ -389,7 +398,6 @@ public class JavaBuilder extends ModuleLevelBuilder { CompileContext context, DiagnosticOutputConsumer diagnosticSink, final OutputFileConsumer outputSink) throws Exception { - LOG.info("Compiling " + files.size() + " java files"); final List options = getCompilationOptions(context, chunk); final ClassProcessingConsumer classesConsumer = new ClassProcessingConsumer(context, outputSink); try { @@ -726,17 +734,23 @@ public class JavaBuilder extends ModuleLevelBuilder { final String customArgs = javacOpts.get("ADDITIONAL_OPTIONS_STRING"); if (customArgs != null) { - final StringTokenizer tokenizer = new StringTokenizer(customArgs, " \t\r\n"); - while (tokenizer.hasMoreTokens()) { - final String token = tokenizer.nextToken(); - if ("-g".equals(token) || "-deprecation".equals(token) || "-nowarn".equals(token) || "-verbose".equals(token)) { + final StringTokenizer customOptsTokenizer = new StringTokenizer(customArgs, " \t\r\n"); + boolean skip = false; + while (customOptsTokenizer.hasMoreTokens()) { + final String userOption = customOptsTokenizer.nextToken(); + if (FILTERED_OPTIONS.contains(userOption)) { + skip = true; continue; } - if (token.startsWith("-J-")) { - vmOptions.add(token.substring("-J".length())); - } - else { - options.add(token); + if (!skip) { + if (!FILTERED_SINGLE_OPTIONS.contains(userOption)) { + if (userOption.startsWith("-J-")) { + vmOptions.add(userOption.substring("-J".length())); + } + else { + options.add(userOption); + } + } } } } diff --git a/jps/jps-builders/src/org/jetbrains/jps/javac/JavacServer.java b/jps/jps-builders/src/org/jetbrains/jps/javac/JavacServer.java index f4dfb849943a..4cb83029243b 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/javac/JavacServer.java +++ b/jps/jps-builders/src/org/jetbrains/jps/javac/JavacServer.java @@ -12,13 +12,12 @@ import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.api.CanceledStatus; +import org.jetbrains.jps.api.SharedThreadPool; import javax.tools.*; import java.io.File; import java.net.InetSocketAddress; import java.util.*; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; /** * @author Eugene Zhuravlev @@ -32,11 +31,9 @@ public class JavacServer { private final ChannelGroup myAllOpenChannels = new DefaultChannelGroup("javac-server"); private final ChannelFactory myChannelFactory; private final ChannelPipelineFactory myPipelineFactory; - private ExecutorService myThreadPool; public JavacServer() { - myThreadPool = Executors.newCachedThreadPool(); - myChannelFactory = new NioServerSocketChannelFactory(myThreadPool, myThreadPool, 1); + myChannelFactory = new NioServerSocketChannelFactory(SharedThreadPool.INSTANCE, SharedThreadPool.INSTANCE, 1); final ChannelRegistrar channelRegistrar = new ChannelRegistrar(); final ChannelHandler compilationRequestsHandler = new CompilationRequestsHandler(); myPipelineFactory = new ChannelPipelineFactory() { @@ -198,10 +195,11 @@ public class JavacServer { final CancelHandler cancelHandler = new CancelHandler(); myCancelHandlers.add(cancelHandler); - myThreadPool.submit(new Runnable() { + SharedThreadPool.INSTANCE.submit(new Runnable() { public void run() { try { - final JavacRemoteProto.Message exitMsg = compile(ctx, sessionId, options, files, cp, platformCp, srcPath, outs, cancelHandler); + final JavacRemoteProto.Message exitMsg = + compile(ctx, sessionId, options, files, cp, platformCp, srcPath, outs, cancelHandler); Channels.write(ctx.getChannel(), exitMsg); } finally { @@ -218,10 +216,14 @@ public class JavacServer { cancelBuilds(); new Thread("StopThread") { public void run() { - JavacServer.this.stop(); + try { + JavacServer.this.stop(); + } + finally { + System.exit(0); + } } }.start(); - //System.exit(0); } else { reply = JavacProtoUtil.toMessage(sessionId, JavacProtoUtil.createFailure("Unsupported request type: " + requestType.name(), null)); diff --git a/jps/jps-builders/src/org/jetbrains/jps/javac/JavacServerBootstrap.java b/jps/jps-builders/src/org/jetbrains/jps/javac/JavacServerBootstrap.java index f2dc1a82a7f0..a43338c9da3e 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/javac/JavacServerBootstrap.java +++ b/jps/jps-builders/src/org/jetbrains/jps/javac/JavacServerBootstrap.java @@ -93,7 +93,7 @@ public class JavacServerBootstrap { processHandler.addProcessListener(new ProcessAdapter() { public void onTextAvailable(ProcessEvent event, Key outputType) { final String text = event.getText(); - if (!StringUtil.isEmpty(text)) { + if (!StringUtil.isEmptyOrSpaces(text)) { if (outputType == ProcessOutputTypes.STDOUT) { System.out.print("JAVAC_SERVER: " + text); } diff --git a/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java b/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java index b2f68adccdee..b051dfa52948 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java +++ b/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java @@ -110,7 +110,7 @@ class OptimizedFileManager extends DefaultFileManager { private boolean isFile(File root) { Boolean cachedIsFile = myIsFile.get(root); if (cachedIsFile == null) { - cachedIsFile = root.isFile(); + cachedIsFile = Boolean.valueOf(root.isFile()); myIsFile.put(root, cachedIsFile); } return cachedIsFile.booleanValue(); diff --git a/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager17.java b/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager17.java index ec894f6ab35b..d0aad87b2381 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager17.java +++ b/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager17.java @@ -164,7 +164,7 @@ class OptimizedFileManager17 extends com.sun.tools.javac.file.JavacFileManager { private boolean isFile(File root) { Boolean cachedIsFile = myIsFile.get(root); if (cachedIsFile == null) { - cachedIsFile = root.isFile(); + cachedIsFile = Boolean.valueOf(root.isFile()); myIsFile.put(root, cachedIsFile); } return cachedIsFile.booleanValue(); diff --git a/jps/jps-builders/testSrc/org/jetbrains/ether/StorageDumper.java b/jps/jps-builders/testSrc/org/jetbrains/ether/StorageDumper.java index bd7049c0a1ce..2105e1747168 100644 --- a/jps/jps-builders/testSrc/org/jetbrains/ether/StorageDumper.java +++ b/jps/jps-builders/testSrc/org/jetbrains/ether/StorageDumper.java @@ -134,6 +134,7 @@ public class StorageDumper { final PrintStream p = new PrintStream(outputPath); mappings.toStream(p); + mappings.close(); p.close(); } diff --git a/jps/lib/optimizedFileManager.jar b/jps/lib/optimizedFileManager.jar index 9765565bf9b7..c3726243b6e6 100644 Binary files a/jps/lib/optimizedFileManager.jar and b/jps/lib/optimizedFileManager.jar differ diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/Mappings.java b/jps/model/src/org/jetbrains/ether/dependencyView/Mappings.java index f90f00941c1f..0ff6160c71d4 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/Mappings.java +++ b/jps/model/src/org/jetbrains/ether/dependencyView/Mappings.java @@ -846,7 +846,7 @@ public class Mappings { } private class Differential { - final int DESPERATE_MASK = Opcodes.ACC_STATIC | Opcodes.ACC_FINAL; + static final int DESPERATE_MASK = Opcodes.ACC_STATIC | Opcodes.ACC_FINAL; final Mappings myDelta; final Collection myRemoved; diff --git a/lib/guava-11.0.1.jar b/lib/guava-11.0.1.jar deleted file mode 100644 index af4a383eff83..000000000000 Binary files a/lib/guava-11.0.1.jar and /dev/null differ diff --git a/lib/guava-12.0.jar b/lib/guava-12.0.jar new file mode 100644 index 000000000000..fefd6b2713c6 Binary files /dev/null and b/lib/guava-12.0.jar differ diff --git a/lib/required_for_dist.txt b/lib/required_for_dist.txt index f63774fa43e8..d822b97af6d3 100644 --- a/lib/required_for_dist.txt +++ b/lib/required_for_dist.txt @@ -13,7 +13,7 @@ commons-net-2.0-patched.jar dtdparser113.jar groovy-all-1.8.5.jar gson-2.2.1.jar -guava-11.0.1.jar +guava-12.0.jar jaxen-1.1.3.jar jcip-annotations.jar jdom.jar diff --git a/lib/src/guava-11.0.1-sources.jar b/lib/src/guava-11.0.1-sources.jar deleted file mode 100644 index 778c0c453d51..000000000000 Binary files a/lib/src/guava-11.0.1-sources.jar and /dev/null differ diff --git a/lib/src/guava-12.0-sources.jar b/lib/src/guava-12.0-sources.jar new file mode 100644 index 000000000000..f6e03018ccdc Binary files /dev/null and b/lib/src/guava-12.0-sources.jar differ diff --git a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionConfidence.java b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionConfidence.java index 9a833e215d1f..10efb39d0846 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionConfidence.java +++ b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionConfidence.java @@ -19,7 +19,6 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.ThreeState; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; /** * @author peter @@ -30,7 +29,7 @@ public abstract class CompletionConfidence { public abstract ThreeState shouldFocusLookup(@NotNull CompletionParameters parameters); @NotNull - public ThreeState shouldSkipAutopopup(@Nullable PsiElement contextElement, @NotNull PsiFile psiFile, int offset) { + public ThreeState shouldSkipAutopopup(@NotNull PsiElement contextElement, @NotNull PsiFile psiFile, int offset) { return ThreeState.UNSURE; } } diff --git a/platform/lang-api/src/com/intellij/codeInsight/completion/SkipAutopopupInStrings.java b/platform/lang-api/src/com/intellij/codeInsight/completion/SkipAutopopupInStrings.java index 699667024930..7b50882ea357 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/completion/SkipAutopopupInStrings.java +++ b/platform/lang-api/src/com/intellij/codeInsight/completion/SkipAutopopupInStrings.java @@ -25,7 +25,6 @@ import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilBase; import com.intellij.util.ThreeState; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; /** * @author peter @@ -39,19 +38,12 @@ public class SkipAutopopupInStrings extends CompletionConfidence { @NotNull @Override - public ThreeState shouldSkipAutopopup(@Nullable PsiElement contextElement, @NotNull PsiFile psiFile, int offset) { - if (contextElement != null) { - ParserDefinition definition = LanguageParserDefinitions.INSTANCE.forLanguage(PsiUtilBase.getLanguageAtOffset(psiFile, offset)); - if (definition != null) { - if (isStringLiteral(contextElement, definition) || isStringLiteral(contextElement.getParent(), definition)) { - return ThreeState.YES; - } - if (offset > 0) { - PsiElement prev = psiFile.findElementAt(offset - 1); - if (prev != null && (isStringLiteralWithError(prev, definition) || isStringLiteralWithError(prev.getParent(), definition))) { - return ThreeState.YES; - } - } + public ThreeState shouldSkipAutopopup(@NotNull PsiElement contextElement, @NotNull PsiFile psiFile, int offset) { + ParserDefinition definition = LanguageParserDefinitions.INSTANCE.forLanguage(PsiUtilBase.getLanguageAtOffset(psiFile, offset)); + if (definition != null) { + if (isStringLiteral(contextElement, definition) || isStringLiteral(contextElement.getParent(), definition) || + isStringLiteralWithError(contextElement, definition) || isStringLiteralWithError(contextElement.getParent(), definition)) { + return ThreeState.YES; } } diff --git a/platform/lang-api/src/com/intellij/facet/frameworks/beans/ArtifactItem.java b/platform/lang-api/src/com/intellij/facet/frameworks/beans/ArtifactItem.java index a53d4a91c5b8..708d1eb28b39 100644 --- a/platform/lang-api/src/com/intellij/facet/frameworks/beans/ArtifactItem.java +++ b/platform/lang-api/src/com/intellij/facet/frameworks/beans/ArtifactItem.java @@ -39,9 +39,18 @@ public class ArtifactItem { @Attribute("url") public String myUrl; + @Attribute("srcUrl") + public String mySourceUrl; + + @Attribute("docUrl") + public String myDocUrl; + @Attribute("md5") public String myMD5; + @Attribute("optional") + public boolean myOptional; + public String getName() { return myName == null ? getNameFromUrl() : myName; } @@ -51,6 +60,18 @@ public class ArtifactItem { return index == -1 ? myUrl : myUrl.substring(index + 1); } + public boolean isOptional() { + return myOptional; + } + + public String getSourceUrl() { + return mySourceUrl; + } + + public String getDocUrl() { + return myDocUrl; + } + public String getUrl() { return myUrl; } diff --git a/platform/lang-api/src/com/intellij/lang/folding/FoldingDescriptor.java b/platform/lang-api/src/com/intellij/lang/folding/FoldingDescriptor.java index 1e066b303a92..1b2253bb7555 100644 --- a/platform/lang-api/src/com/intellij/lang/folding/FoldingDescriptor.java +++ b/platform/lang-api/src/com/intellij/lang/folding/FoldingDescriptor.java @@ -94,7 +94,7 @@ public class FoldingDescriptor { @Nullable FoldingGroup group, Set dependencies, boolean neverExpands) { - assert range.getStartOffset() + 1 < range.getEndOffset() : range + ", text: " + node.getText(); + assert range.getStartOffset() + 1 < range.getEndOffset() : range + ", text: " + node.getText() + ", language = " + node.getPsi().getLanguage(); myElement = node; ProperTextRange.assertProperRange(range); myRange = range; diff --git a/platform/lang-api/src/com/intellij/util/download/FileDownloader.java b/platform/lang-api/src/com/intellij/util/download/FileDownloader.java index 322c0cdf568d..374dcf8c1a30 100644 --- a/platform/lang-api/src/com/intellij/util/download/FileDownloader.java +++ b/platform/lang-api/src/com/intellij/util/download/FileDownloader.java @@ -15,10 +15,13 @@ */ package com.intellij.util.download; +import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.List; + /** * Use {@link DownloadableFileService} to create instances of this interface * @@ -39,4 +42,11 @@ public interface FileDownloader { */ @Nullable VirtualFile[] download(); + + /** + * Download files with modal progress dialog. + * @return downloaded files with corresponding descriptions + */ + @Nullable + List> downloadAndReturnWithDescriptions(); } 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 2e1333b0919c..c5ed564d4f56 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java @@ -221,17 +221,18 @@ public class CodeCompletionHandlerBase implements CodeInsightActionHandler { CommandProcessor.getInstance().runUndoTransparentAction(initCmd); int offset = editor.getCaretModel().getOffset(); - int psiOffset = Math.max(0, offset); + int psiOffset = Math.max(0, offset - 1); PsiElement elementAt = InjectedLanguageUtil.findInjectedElementNoCommit(psiFile, psiOffset); if (elementAt == null) { elementAt = psiFile.findElementAt(psiOffset); } + if (elementAt == null) return; - Language language = elementAt != null ? PsiUtilBase.findLanguageFromElement(elementAt):psiFile.getLanguage(); + Language language = PsiUtilBase.findLanguageFromElement(elementAt); for (CompletionConfidence confidence : CompletionConfidenceEP.forLanguage(language)) { - final ThreeState result = confidence.shouldSkipAutopopup(elementAt, psiFile, offset); // TODO: Peter Lazy API + final ThreeState result = confidence.shouldSkipAutopopup(elementAt, psiFile, offset); if (result == ThreeState.YES) return; if (result == ThreeState.NO) break; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CutHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CutHandler.java index 0dd4089b585f..83efc9586d8a 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CutHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CutHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorModificationUtil; import com.intellij.openapi.editor.SelectionModel; +import com.intellij.openapi.editor.VisualPosition; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.editor.actionSystem.EditorActionManager; import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler; @@ -55,8 +56,10 @@ public class CutHandler extends EditorWriteActionHandler { return; } + VisualPosition positionToRestore = null; SelectionModel selectionModel = editor.getSelectionModel(); if (!selectionModel.hasSelection() && !selectionModel.hasBlockSelection()) { + positionToRestore = editor.getCaretModel().getVisualPosition(); selectionModel.selectLineAtCaret(); if (!selectionModel.hasSelection()) return; } @@ -64,5 +67,8 @@ public class CutHandler extends EditorWriteActionHandler { EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_COPY).execute(editor, dataContext); EditorModificationUtil.deleteSelectedText(editor); + if (positionToRestore != null) { + editor.getCaretModel().moveToVisualPosition(positionToRestore); + } } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupManagerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupManagerImpl.java index ed9fbc348937..6de987b26205 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupManagerImpl.java @@ -113,7 +113,7 @@ public class LookupManagerImpl extends LookupManager { } LookupImpl lookup = createLookup(editor, items, prefix, arranger); - return lookup.showLookup() ? lookup : null; + return lookup != null && lookup.showLookup() ? lookup : null; } public LookupImpl createLookup(final Editor editor, diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java index 7a7c661e3dcd..87e76ffe3409 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java @@ -33,10 +33,7 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PathMacroManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.progress.Task; +import com.intellij.openapi.progress.*; import com.intellij.openapi.progress.impl.ProgressManagerImpl; import com.intellij.openapi.progress.util.ProgressWrapper; import com.intellij.openapi.project.DumbService; @@ -271,12 +268,19 @@ public class GlobalInspectionContextImpl extends UserDataHolderBase implements G getContentManager().removeContent(myContent, true); } - ApplicationManager.getApplication().invokeLater(new Runnable() { + Runnable runnable = new Runnable() { public void run() { myCurrentScope = scope; launchInspections(scope, manager); } - }); + }; + + if (ApplicationManager.getApplication().isUnitTestMode()) { + runnable.run(); + } + else { + ApplicationManager.getApplication().invokeLater(runnable); + } } @@ -483,7 +487,7 @@ public class GlobalInspectionContextImpl extends UserDataHolderBase implements G public void performInspectionsWithProgress(@NotNull final AnalysisScope scope, @NotNull final InspectionManager manager) { final PsiManager psiManager = PsiManager.getInstance(myProject); - myProgressIndicator = ProgressManager.getInstance().getProgressIndicator(); + myProgressIndicator = ApplicationManager.getApplication().isUnitTestMode() ? new EmptyProgressIndicator() : ProgressManager.getInstance().getProgressIndicator(); //init manager in read action RefManagerImpl refManager = (RefManagerImpl)getRefManager(); try { @@ -714,7 +718,7 @@ public class GlobalInspectionContextImpl extends UserDataHolderBase implements G } protected List getUsedTools() { - InspectionProfileImpl profile = (InspectionProfileImpl)getCurrentProfile(); + InspectionProfileImpl profile = new InspectionProfileImpl((InspectionProfileImpl)getCurrentProfile()); List tools = profile.getAllEnabledInspectionTools(myProject); THashSet set = null; for (ToolsImpl tool : tools) { diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java index a9698f2f37a9..f42c5b62f97e 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java @@ -92,7 +92,7 @@ public class InspectionProfileImpl extends ProfileEx implements ModifiableModel, private boolean myModified = false; private volatile boolean myInitialized; - private InspectionProfileImpl(@NotNull InspectionProfileImpl inspectionProfile) { + InspectionProfileImpl(@NotNull InspectionProfileImpl inspectionProfile) { super(inspectionProfile.getName()); myRegistrar = inspectionProfile.myRegistrar; diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java index a476cef85d14..58ba805b5f96 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java @@ -453,9 +453,11 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, if (each.getType() instanceof UnknownConfigurationType) continue; recentList.add(getUniqueName(each)); } - final Element recent = new Element(RECENT); - parentNode.addContent(recent); - recentList.writeExternal(recent); + if (!recentList.isEmpty()) { + final Element recent = new Element(RECENT); + parentNode.addContent(recent); + recentList.writeExternal(recent); + } if (myUnknownElements != null) { for (Element unloadedElement : myUnknownElements) { @@ -771,7 +773,9 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, invalidateConfigurationIcon(settings); settings.setTemporary(false); myRecentlyUsedTemporaries.remove(configuration); - setOrdered(false); + if (!myOrder.isEmpty()) { + setOrdered(false); + } fireRunConfigurationChanged(settings); } } diff --git a/platform/lang-impl/src/com/intellij/execution/rmi/RemoteProcessSupport.java b/platform/lang-impl/src/com/intellij/execution/rmi/RemoteProcessSupport.java index 7d4ec2fefb58..767a0595abf6 100644 --- a/platform/lang-impl/src/com/intellij/execution/rmi/RemoteProcessSupport.java +++ b/platform/lang-impl/src/com/intellij/execution/rmi/RemoteProcessSupport.java @@ -117,6 +117,7 @@ public abstract class RemoteProcessSupport { startProcess(target, configuration, key); if (ref.isNull()) { try { + //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (ref) { while (ref.isNull()) { ref.wait(1000); @@ -176,6 +177,7 @@ public abstract class RemoteProcessSupport { try { final RunProfileState state = getRunProfileState(target, configuration, executor); final ExecutionResult result = state.execute(executor, runner); + //noinspection ConstantConditions processHandler = result.getProcessHandler(); } catch (Exception e) { @@ -210,6 +212,7 @@ public abstract class RemoteProcessSupport { } if (info != null) { if (info instanceof Info) { + //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (ref) { ref.set((Info)info); ref.notifyAll(); @@ -239,6 +242,7 @@ public abstract class RemoteProcessSupport { } private static T narrowImpl(Remote remote, Class to) { + //noinspection unchecked return (T)(to.isInstance(remote) ? remote : PortableRemoteObject.narrow(remote, to)); } @@ -282,7 +286,7 @@ public abstract class RemoteProcessSupport { info = (PendingInfo)o; if (outputType == ProcessOutputTypes.STDOUT) { final String prefix = "Port/ID:"; - if (text != null && text.startsWith(prefix)) { + if (text.startsWith(prefix)) { final String pair = text.substring(prefix.length()).trim(); final int idx = pair.indexOf("/"); result = new Info(info.handler, Integer.parseInt(pair.substring(0, idx)), pair.substring(idx + 1)); @@ -304,12 +308,18 @@ public abstract class RemoteProcessSupport { info.ref.notifyAll(); } fireModificationCountChanged(); + try { + RemoteDeadHand.TwoMinutesTurkish.startCooking("localhost", result.port); + } + catch (Exception e) { + LOG.error(e); + } } } }; } - private void handleProcessTerminated(Pair key, String errorMessage) { + private void handleProcessTerminated(Pair key, @Nullable String errorMessage) { Object o; final PendingInfo pendingInfo; synchronized (myProcMap) { diff --git a/platform/lang-impl/src/com/intellij/framework/library/DownloadableLibraryFileDescription.java b/platform/lang-impl/src/com/intellij/framework/library/DownloadableLibraryFileDescription.java new file mode 100644 index 000000000000..6896cde44c21 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/framework/library/DownloadableLibraryFileDescription.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.framework.library; + +import com.intellij.util.download.DownloadableFileDescription; +import org.jetbrains.annotations.Nullable; + +/** + * @author nik + */ +public interface DownloadableLibraryFileDescription extends DownloadableFileDescription { + @Nullable + DownloadableFileDescription getSourcesDescription(); + + @Nullable + DownloadableFileDescription getDocumentationDescription(); + + boolean isOptional(); + +} diff --git a/platform/lang-impl/src/com/intellij/framework/library/FrameworkLibraryVersion.java b/platform/lang-impl/src/com/intellij/framework/library/FrameworkLibraryVersion.java index 71612c602580..75c419ef8232 100644 --- a/platform/lang-impl/src/com/intellij/framework/library/FrameworkLibraryVersion.java +++ b/platform/lang-impl/src/com/intellij/framework/library/FrameworkLibraryVersion.java @@ -18,10 +18,16 @@ package com.intellij.framework.library; import com.intellij.util.download.DownloadableFileSetDescription; import org.jetbrains.annotations.NotNull; +import java.util.List; + /** * @author nik */ public interface FrameworkLibraryVersion extends DownloadableFileSetDescription { @NotNull String getDefaultLibraryName(); + + @NotNull + @Override + List getFiles(); } diff --git a/platform/lang-impl/src/com/intellij/framework/library/impl/DownloadableLibraryFileDescriptionImpl.java b/platform/lang-impl/src/com/intellij/framework/library/impl/DownloadableLibraryFileDescriptionImpl.java new file mode 100644 index 000000000000..c3e1c86b0c12 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/framework/library/impl/DownloadableLibraryFileDescriptionImpl.java @@ -0,0 +1,57 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.framework.library.impl; + +import com.intellij.framework.library.DownloadableLibraryFileDescription; +import com.intellij.util.download.impl.DownloadableFileDescriptionImpl; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * @author nik + */ +public class DownloadableLibraryFileDescriptionImpl extends DownloadableFileDescriptionImpl implements DownloadableLibraryFileDescription { + private DownloadableFileDescriptionImpl mySourceDownloadUrl; + private DownloadableFileDescriptionImpl myDocumentationDownloadUrl; + private boolean myOptional; + + public DownloadableLibraryFileDescriptionImpl(@NotNull String downloadUrl, + @NotNull String fileName, + @NotNull String fileExtension, + @Nullable String sourceDownloadUrl, + @Nullable String documentationDownloadUrl, + boolean optional) { + super(downloadUrl, fileName, fileExtension); + mySourceDownloadUrl = sourceDownloadUrl != null ? new DownloadableFileDescriptionImpl(sourceDownloadUrl, fileName +"-sources", fileExtension) : null; + myDocumentationDownloadUrl = documentationDownloadUrl != null ? new DownloadableFileDescriptionImpl(documentationDownloadUrl, fileName+"-javadoc", fileExtension) : null; + myOptional = optional; + } + + @Override + public DownloadableFileDescriptionImpl getSourcesDescription() { + return mySourceDownloadUrl; + } + + @Override + public DownloadableFileDescriptionImpl getDocumentationDescription() { + return myDocumentationDownloadUrl; + } + + @Override + public boolean isOptional() { + return myOptional; + } +} diff --git a/platform/lang-impl/src/com/intellij/framework/library/impl/FrameworkLibraryVersionImpl.java b/platform/lang-impl/src/com/intellij/framework/library/impl/FrameworkLibraryVersionImpl.java index 494645e578a7..79cb2df83d75 100644 --- a/platform/lang-impl/src/com/intellij/framework/library/impl/FrameworkLibraryVersionImpl.java +++ b/platform/lang-impl/src/com/intellij/framework/library/impl/FrameworkLibraryVersionImpl.java @@ -15,8 +15,8 @@ */ package com.intellij.framework.library.impl; +import com.intellij.framework.library.DownloadableLibraryFileDescription; import com.intellij.framework.library.FrameworkLibraryVersion; -import com.intellij.util.download.DownloadableFileDescription; import com.intellij.util.download.impl.DownloadableFileSetDescriptionImpl; import org.jetbrains.annotations.NotNull; @@ -25,11 +25,11 @@ import java.util.List; /** * @author nik */ -public class FrameworkLibraryVersionImpl extends DownloadableFileSetDescriptionImpl implements FrameworkLibraryVersion { +public class FrameworkLibraryVersionImpl extends DownloadableFileSetDescriptionImpl implements FrameworkLibraryVersion { private final String myLibraryCategory; public FrameworkLibraryVersionImpl(String versionString, - List libraryFiles, + List libraryFiles, String category) { super(category, versionString, libraryFiles); myLibraryCategory = category; diff --git a/platform/lang-impl/src/com/intellij/framework/library/impl/LibraryVersionsFetcher.java b/platform/lang-impl/src/com/intellij/framework/library/impl/LibraryVersionsFetcher.java index fad40e2cc26d..f9d58c5f4f55 100644 --- a/platform/lang-impl/src/com/intellij/framework/library/impl/LibraryVersionsFetcher.java +++ b/platform/lang-impl/src/com/intellij/framework/library/impl/LibraryVersionsFetcher.java @@ -16,9 +16,11 @@ package com.intellij.framework.library.impl; import com.intellij.facet.frameworks.beans.Artifact; -import com.intellij.util.download.DownloadableFileDescription; +import com.intellij.facet.frameworks.beans.ArtifactItem; import com.intellij.framework.library.DownloadableLibraryDescription; +import com.intellij.framework.library.DownloadableLibraryFileDescription; import com.intellij.framework.library.FrameworkLibraryVersion; +import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.download.impl.FileSetVersionsFetcherBase; import org.jetbrains.annotations.NotNull; @@ -28,14 +30,27 @@ import java.util.List; /** * @author nik */ -public class LibraryVersionsFetcher extends FileSetVersionsFetcherBase implements DownloadableLibraryDescription { +public class LibraryVersionsFetcher extends FileSetVersionsFetcherBase implements DownloadableLibraryDescription { public LibraryVersionsFetcher(@NotNull String groupId, @NotNull URL[] localUrls) { super(groupId, localUrls); } @Override - protected FrameworkLibraryVersion createVersion(Artifact version, List files) { + protected FrameworkLibraryVersion createVersion(Artifact version, List files) { return new FrameworkLibraryVersionImpl(version.getVersion(), files, myGroupId); } + + protected DownloadableLibraryFileDescription createFileDescription(ArtifactItem item, String url, String prefix) { + String sourceUrl = item.getSourceUrl(); + if (sourceUrl != null) { + sourceUrl = prependPrefix(sourceUrl, prefix); + } + String docUrl = item.getDocUrl(); + if (docUrl != null) { + docUrl = prependPrefix(docUrl, prefix); + } + final String name = item.getName(); + return new DownloadableLibraryFileDescriptionImpl(url, FileUtil.getNameWithoutExtension(name), FileUtil.getExtension(name), sourceUrl, docUrl, item.isOptional()); + } } diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java index c3839457750b..208f6e1778a8 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java @@ -61,6 +61,7 @@ import com.intellij.ui.popup.PopupUpdateProcessor; import com.intellij.usageView.UsageInfo; import com.intellij.usages.*; import com.intellij.util.Alarm; +import com.intellij.util.PlatformUtils; import com.intellij.util.Processor; import com.intellij.util.diff.Diff; import com.intellij.util.diff.FilesTooBigForDiffException; @@ -195,7 +196,7 @@ public abstract class ChooseByNameBase { } public boolean isSearchInAnyPlace() { - return mySearchInAnyPlace; + return PlatformUtils.isCidr() || mySearchInAnyPlace; } public void setSearchInAnyPlace(boolean searchInAnyPlace) { diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultChooseByNameItemProvider.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultChooseByNameItemProvider.java index 7fbc2a2fdbd4..23bc20e3721d 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultChooseByNameItemProvider.java +++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/DefaultChooseByNameItemProvider.java @@ -19,6 +19,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; +import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; @@ -32,10 +33,7 @@ import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nullable; import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; +import java.util.*; public class DefaultChooseByNameItemProvider implements ChooseByNameItemProvider { private static final Logger LOG = Logger.getInstance("#com.intellij.ide.util.gotoByName.ChooseByNameIdea"); @@ -53,21 +51,41 @@ public class DefaultChooseByNameItemProvider implements ChooseByNameItemProvider Processor consumer) { String namePattern = getNamePattern(base, pattern); String qualifierPattern = getQualifierPattern(base, pattern); + String modifiedNamePattern = null; if (base.isSearchInAnyPlace() && !namePattern.trim().isEmpty()) { - namePattern = "*" + namePattern + "*"; + modifiedNamePattern = "*" + namePattern + "*"; } boolean empty = namePattern.isEmpty() || namePattern.equals("@"); // TODO[yole]: remove implicit dependency if (empty && !base.canShowListForEmptyPattern()) return; List namesList = new ArrayList(); - getNamesByPattern(base, base.getNames(everywhere), cancelled, namesList, namePattern); + String[] names = base.getNames(everywhere); + getNamesByPattern(base, names, cancelled, namesList, namePattern); if (cancelled.compute()) { throw new ProcessCanceledException(); } sortNamesList(namePattern, namesList); + if (modifiedNamePattern != null) { + final Set matched = new HashSet(namesList); + List additionalNamesList = new ArrayList(); + namePattern = modifiedNamePattern; + getNamesByPattern(base, names, cancelled, additionalNamesList, namePattern); + additionalNamesList = ContainerUtil.filter(additionalNamesList, new Condition() { + @Override + public boolean value(String name) { + return !matched.contains(name); + } + }); + sortNamesList(namePattern, additionalNamesList); + namesList.addAll(additionalNamesList); + } + + if (cancelled.compute()) { + throw new ProcessCanceledException(); + } List sameNameElements = new SmartList(); diff --git a/platform/lang-impl/src/com/intellij/indentation/IndentationFoldingBuilder.java b/platform/lang-impl/src/com/intellij/indentation/IndentationFoldingBuilder.java index b084041e699a..447158cc029f 100644 --- a/platform/lang-impl/src/com/intellij/indentation/IndentationFoldingBuilder.java +++ b/platform/lang-impl/src/com/intellij/indentation/IndentationFoldingBuilder.java @@ -32,7 +32,7 @@ public abstract class IndentationFoldingBuilder implements FoldingBuilder, DumbA private void collectDescriptors(@NotNull final ASTNode node, @NotNull final List descriptors) { final ASTNode[] children = node.getChildren(myTokenSet); if (children.length > 0) { - if (node.getTreeParent() !=null && node.getTextLength() > 0) { + if (node.getTreeParent() !=null && node.getTextLength() > 1) { descriptors.add(new FoldingDescriptor(node, node.getTextRange())); } for (ASTNode child : children) { @@ -45,14 +45,41 @@ public abstract class IndentationFoldingBuilder implements FoldingBuilder, DumbA public String getPlaceholderText(@NotNull final ASTNode node) { final StringBuilder builder = new StringBuilder(); ASTNode child = node.getFirstChildNode(); - String text; - while (child != null && (text = child.getText()) != null && !text.contains("\n")){ - builder.append(text); + while (child != null) { + String text = child.getText(); + if (text == null) { + if (builder.length() > 0) { + break; + } + } + else if (!text.contains("\n")) { + builder.append(text); + } + else if (builder.length() > 0) { + builder.append(text.substring(0, text.indexOf('\n'))); + break; + } + else { + builder.append(getFirstNonEmptyLine(text)); + if (builder.length() > 0) { + break; + } + } child = child.getTreeNext(); } return builder.toString(); } + @NotNull + private static String getFirstNonEmptyLine(@NotNull final String text) { + int start = 0; + int end; + while ((end = text.indexOf('\n', start)) != -1 && start >= end) { + start = end + 1; + } + return end == -1 ? text.substring(start) : text.substring(start, end); + } + public boolean isCollapsedByDefault(@NotNull ASTNode node) { return false; } diff --git a/platform/lang-impl/src/com/intellij/indentation/IndentationParser.java b/platform/lang-impl/src/com/intellij/indentation/IndentationParser.java index 7edfc9f94405..8ac2a889a340 100644 --- a/platform/lang-impl/src/com/intellij/indentation/IndentationParser.java +++ b/platform/lang-impl/src/com/intellij/indentation/IndentationParser.java @@ -40,43 +40,46 @@ public abstract class IndentationParser implements PsiParser { // EOL if (type == myEolTokenType) { // Handle variant with several EOLs - if (startLineMarker == null){ + if (startLineMarker == null) { startLineMarker = builder.mark(); } eolSeen = true; - } else - - // Indent - { - if (type == myIndentTokenType){ + } + else { + if (type == myIndentTokenType) { //noinspection ConstantConditions currentIndent = builder.getTokenText().length(); - } else - - if (eolSeen) { - if (startLineMarker != null){ - startLineMarker.rollbackTo(); - startLineMarker = null; + } + else { + if (!eolSeen && !stack.isEmpty() && currentIndent > 0 && currentIndent < stack.peek().first) { + // sometimes we do not have EOL between indents + eolSeen = true; } - // Close indentation blocks - while (!stack.isEmpty() && currentIndent < stack.peek().first){ - stack.pop().second.done(myBlockElementType); - } - - if (!stack.isEmpty()) { - final Pair pair = stack.peek(); - if (currentIndent == pair.first) { + if (eolSeen) { + if (startLineMarker != null) { + startLineMarker.rollbackTo(); + startLineMarker = null; + } + // Close indentation blocks + while (!stack.isEmpty() && currentIndent < stack.peek().first){ stack.pop().second.done(myBlockElementType); - passEOLsAndIndents(builder); - stack.push(Pair.create(currentIndent, builder.mark())); } - if (currentIndent > pair.first) { - passEOLsAndIndents(builder); - stack.push(Pair.create(currentIndent, builder.mark())); + + if (!stack.isEmpty()) { + final Pair pair = stack.peek(); + if (currentIndent == pair.first) { + stack.pop().second.done(myBlockElementType); + passEOLsAndIndents(builder); + stack.push(Pair.create(currentIndent, builder.mark())); + } + if (currentIndent > pair.first) { + passEOLsAndIndents(builder); + stack.push(Pair.create(currentIndent, builder.mark())); + } } + eolSeen = false; + currentIndent = 0; } - eolSeen = false; - currentIndent = 0; } } advanceLexer(builder); diff --git a/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java b/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java index ff65a900ea5a..48f1e2d4c506 100644 --- a/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java +++ b/platform/lang-impl/src/com/intellij/internal/psiView/ViewerTreeStructure.java @@ -144,9 +144,7 @@ public class ViewerTreeStructure extends AbstractTreeStructure { return new Inject(InjectedLanguageManager.getInstance(((PsiFile)element).getProject()).getInjectionHost(((PsiFile)element)), (PsiElement)element); } - return element instanceof Inject - ? ((Inject)element).getParent() - : InjectedLanguageManager.getInstance(((PsiElement)element).getProject()).getInjectionHost(((PsiElement)element)); + return element instanceof Inject ? ((Inject)element).getParent() : ((PsiElement)element).getContext(); } @Override diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionConfigTreeNode.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionConfigTreeNode.java index 9b22317381e7..b28b82abd186 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionConfigTreeNode.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionConfigTreeNode.java @@ -20,6 +20,7 @@ */ package com.intellij.profile.codeInspection.ui; +import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.ex.Descriptor; import com.intellij.codeInspection.ex.ScopeToolState; import com.intellij.openapi.util.NotNullLazyValue; @@ -108,4 +109,15 @@ public class InspectionConfigTreeNode extends CheckedTreeNode { public void dropCache() { myProperSetting.drop(); } + + @Override + public String toString() { + if (userObject instanceof Descriptor) { + final String displayNameByKey = HighlightDisplayKey.getDisplayNameByKey(((Descriptor)userObject).getKey()); + if (displayNameByKey != null) { + return displayNameByKey; + } + } + return super.toString(); + } } \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeFileBase.java b/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeFileBase.java index b5e1eacc1b32..6034abe3cbe2 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeFileBase.java +++ b/platform/lang-impl/src/com/intellij/refactoring/lang/ExtractIncludeFileBase.java @@ -232,6 +232,7 @@ public abstract class ExtractIncludeFileBase implements Re } }); final String includePath = processPrimaryFragment(first, second, targetDirectory, targetfileName, file); + editor.getCaretModel().moveToOffset(first.getTextRange().getStartOffset()); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java index 9439abe27109..293ab0095f42 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java @@ -71,6 +71,8 @@ import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.ui.awt.RelativePoint; +import com.intellij.util.CommonProcessors; +import com.intellij.util.Query; import com.intellij.util.containers.Stack; import com.intellij.util.ui.PositionTracker; import org.jetbrains.annotations.NonNls; @@ -220,8 +222,22 @@ public abstract class InplaceRefactoring { return new MyLookupExpression(getInitialName(), myNameSuggestions, myElementToRename, shouldSelectAll(), myAdvertisementText); } + protected boolean acceptReference(PsiReference reference) { + return true; + } + protected Collection collectRefs(SearchScope referencesSearchScope) { - return ReferencesSearch.search(myElementToRename, referencesSearchScope, false).findAll(); + final Query search = ReferencesSearch.search(myElementToRename, referencesSearchScope, false); + + final CommonProcessors.CollectProcessor processor = new CommonProcessors.CollectProcessor() { + @Override + protected boolean accept(PsiReference reference) { + return acceptReference(reference); + } + }; + + search.forEach(processor); + return processor.getResults(); } protected boolean buildTemplateAndStart(final Collection refs, diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/VariableInplaceRenamer.java b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/VariableInplaceRenamer.java index 8894c2cc7c71..f52e6635ef16 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/VariableInplaceRenamer.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/VariableInplaceRenamer.java @@ -156,6 +156,11 @@ public class VariableInplaceRenamer extends InplaceRefactoring { } } + @Override + protected int restoreCaretOffset(int offset) { + return offset; + } + @Override protected boolean shouldSelectAll() { if (myEditor.getSettings().isPreselectRename()) return true; diff --git a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java index 92ce9a481739..7dc8e6b4238a 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java +++ b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java @@ -129,10 +129,8 @@ public class SafeDeleteHandler implements RefactoringActionHandler { }; - if (elementsToDelete.length > 0) { - SafeDeleteDialog dialog = new SafeDeleteDialog(project, elementsToDelete, callback); - dialog.show(); - } + SafeDeleteDialog dialog = new SafeDeleteDialog(project, elementsToDelete, callback); + dialog.show(); } } } diff --git a/platform/lang-impl/src/com/intellij/ui/popup/util/DetailViewImpl.java b/platform/lang-impl/src/com/intellij/ui/popup/util/DetailViewImpl.java index b230f482cad1..4327addc74c9 100644 --- a/platform/lang-impl/src/com/intellij/ui/popup/util/DetailViewImpl.java +++ b/platform/lang-impl/src/com/intellij/ui/popup/util/DetailViewImpl.java @@ -52,12 +52,6 @@ public class DetailViewImpl extends JPanel implements DetailView { private JLabel myNothingToShowInEditor = new JLabel("Nothing to show"); private RangeHighlighter myHighlighter; - public void setScheme(EditorColorsScheme scheme) { - myScheme = scheme; - } - - private EditorColorsScheme myScheme = EditorColorsManager.getInstance().getGlobalScheme(); - public DetailViewImpl(Project project) { super(new BorderLayout()); myProject = project; @@ -120,7 +114,7 @@ public class DetailViewImpl extends JPanel implements DetailView { remove(myNothingToShowInEditor); setEditor(EditorFactory.getInstance().createViewer(document, project)); - final EditorColorsScheme scheme = getScheme(); + final EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); EditorHighlighter highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(file, scheme, project); @@ -155,11 +149,6 @@ public class DetailViewImpl extends JPanel implements DetailView { } } - public EditorColorsScheme getScheme() { - return myScheme; - } - - private void clearHightlighting() { if (myHighlighter != null) { diff --git a/platform/lang-impl/src/com/intellij/util/download/impl/DownloadableFileServiceImpl.java b/platform/lang-impl/src/com/intellij/util/download/impl/DownloadableFileServiceImpl.java index 3e653aa96420..5866399506dd 100644 --- a/platform/lang-impl/src/com/intellij/util/download/impl/DownloadableFileServiceImpl.java +++ b/platform/lang-impl/src/com/intellij/util/download/impl/DownloadableFileServiceImpl.java @@ -16,6 +16,7 @@ package com.intellij.util.download.impl; import com.intellij.facet.frameworks.beans.Artifact; +import com.intellij.facet.frameworks.beans.ArtifactItem; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.download.*; @@ -40,10 +41,14 @@ public class DownloadableFileServiceImpl extends DownloadableFileService { @Override public DownloadableFileSetVersions createFileSetVersions(@Nullable String groupId, @NotNull URL... localUrls) { - return new FileSetVersionsFetcherBase(groupId, localUrls) { + return new FileSetVersionsFetcherBase(groupId, localUrls) { @Override protected DownloadableFileSetDescription createVersion(Artifact version, List files) { - return new DownloadableFileSetDescriptionImpl(version.getName(), version.getVersion(), files); + return new DownloadableFileSetDescriptionImpl(version.getName(), version.getVersion(), files); + } + + protected DownloadableFileDescription createFileDescription(ArtifactItem item, String url, String prefix) { + return getInstance().createFileDescription(url, item.getName()); } }; } diff --git a/platform/lang-impl/src/com/intellij/util/download/impl/DownloadableFileSetDescriptionImpl.java b/platform/lang-impl/src/com/intellij/util/download/impl/DownloadableFileSetDescriptionImpl.java index f9ebccbfcef6..e6e40bfdadb7 100644 --- a/platform/lang-impl/src/com/intellij/util/download/impl/DownloadableFileSetDescriptionImpl.java +++ b/platform/lang-impl/src/com/intellij/util/download/impl/DownloadableFileSetDescriptionImpl.java @@ -24,14 +24,14 @@ import java.util.List; /** * @author nik */ -public class DownloadableFileSetDescriptionImpl implements DownloadableFileSetDescription { - protected final List myFiles; +public class DownloadableFileSetDescriptionImpl implements DownloadableFileSetDescription { + protected final List myFiles; protected final String myVersionString; private final String myName; public DownloadableFileSetDescriptionImpl(@NotNull String name, @NotNull String versionString, - @NotNull List files) { + @NotNull List files) { myName = name; myVersionString = versionString; myFiles = files; @@ -51,7 +51,7 @@ public class DownloadableFileSetDescriptionImpl implements DownloadableFileSetDe @NotNull @Override - public List getFiles() { + public List getFiles() { return myFiles; } } diff --git a/platform/lang-impl/src/com/intellij/util/download/impl/FileDownloaderImpl.java b/platform/lang-impl/src/com/intellij/util/download/impl/FileDownloaderImpl.java index 1fc41f0cf8ae..4b9620af0154 100644 --- a/platform/lang-impl/src/com/intellij/util/download/impl/FileDownloaderImpl.java +++ b/platform/lang-impl/src/com/intellij/util/download/impl/FileDownloaderImpl.java @@ -33,10 +33,7 @@ import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VfsUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.VirtualFileManager; +import com.intellij.openapi.vfs.*; import com.intellij.util.download.DownloadableFileDescription; import com.intellij.util.download.FileDownloader; import com.intellij.util.io.UrlConnectionUtil; @@ -87,6 +84,18 @@ public class FileDownloaderImpl implements FileDownloader { @Override public VirtualFile[] download() { + final List> pairs = downloadAndReturnWithDescriptions(); + if (pairs == null) return null; + + List files = new ArrayList(); + for (Pair pair : pairs) { + files.add(pair.getFirst()); + } + return VfsUtilCore.toVirtualFileArray(files); + } + + @Override + public List> downloadAndReturnWithDescriptions() { VirtualFile dir = null; if (myDirectoryForDownloadedFilesPath != null) { File ioDir = new File(FileUtil.toSystemDependentName(myDirectoryForDownloadedFilesPath)); @@ -105,13 +114,13 @@ public class FileDownloaderImpl implements FileDownloader { } @Nullable - private VirtualFile[] doDownload(final VirtualFile dir) { + private List> doDownload(final VirtualFile dir) { HttpConfigurable.getInstance().setAuthenticator(); - final List> downloadedFiles = new ArrayList>(); - final List existingFiles = new ArrayList(); + final List> downloadedFiles = new ArrayList>(); + final List> existingFiles = new ArrayList>(); final Ref exceptionRef = Ref.create(null); final Ref currentFile = new Ref(); - final File ioDir = VfsUtil.virtualToIoFile(dir); + final File ioDir = VfsUtilCore.virtualToIoFile(dir); ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { @Override @@ -130,7 +139,7 @@ public class FileDownloaderImpl implements FileDownloader { long size = existing.exists() ? existing.length() : -1; if (!download(description, size, downloadedFiles)) { - existingFiles.add(existing); + existingFiles.add(Pair.create(existing, description)); } } } @@ -182,16 +191,16 @@ public class FileDownloaderImpl implements FileDownloader { } @NotNull - private static VirtualFile[] moveToDir(final List existingFiles, final List> downloadedFiles, final VirtualFile dir) throws IOException { - List files = new ArrayList(); + private static List> moveToDir(final List> existingFiles, final List> downloadedFiles, final VirtualFile dir) throws IOException { + List> result = new ArrayList>(); - final File ioDir = VfsUtil.virtualToIoFile(dir); - for (Pair pair : downloadedFiles) { - final DownloadableFileDescription description = pair.getFirst(); + final File ioDir = VfsUtilCore.virtualToIoFile(dir); + for (Pair pair : downloadedFiles) { + final DownloadableFileDescription description = pair.getSecond(); final boolean dontTouch = description.getDownloadUrl().startsWith(LIB_SCHEMA) || description.getDownloadUrl().startsWith(LocalFileSystem.PROTOCOL_PREFIX); - final File toFile = dontTouch? pair.getSecond() : generateName(description, ioDir); + final File toFile = dontTouch? pair.getFirst() : generateName(description, ioDir); if (!dontTouch) { - FileUtil.rename(pair.getSecond(), toFile); + FileUtil.rename(pair.getFirst(), toFile); } VirtualFile file = new WriteAction() { @Override @@ -202,24 +211,24 @@ public class FileDownloaderImpl implements FileDownloader { } }.execute().getResultObject(); if (file != null) { - files.add(file); + result.add(Pair.create(file, description)); } } - for (final File file : existingFiles) { + for (final Pair pair : existingFiles) { VirtualFile libraryRootFile = new WriteAction() { @Override protected void run(final Result result) { - final String url = VfsUtil.getUrlForLibraryRoot(file); + final String url = VfsUtil.getUrlForLibraryRoot(pair.getFirst()); result.setResult(VirtualFileManager.getInstance().refreshAndFindFileByUrl(url)); } }.execute().getResultObject(); if (libraryRootFile != null) { - files.add(libraryRootFile); + result.add(Pair.create(libraryRootFile, pair.getSecond())); } } - return VfsUtil.toVirtualFileArray(files); + return result; } private static File generateName(DownloadableFileDescription info, final File dir) { @@ -232,16 +241,16 @@ public class FileDownloaderImpl implements FileDownloader { return new File(dir, fileName); } - private static void deleteFiles(final List> pairs) { - for (Pair pair : pairs) { - FileUtil.delete(pair.getSecond()); + private static void deleteFiles(final List> pairs) { + for (Pair pair : pairs) { + FileUtil.delete(pair.getFirst()); } pairs.clear(); } private static boolean download(final DownloadableFileDescription fileDescription, final long existingFileSize, - final List> downloadedFiles) throws IOException { + final List> downloadedFiles) throws IOException { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); final String presentableUrl = fileDescription.getPresentableDownloadUrl(); final String url = fileDescription.getDownloadUrl(); @@ -249,13 +258,13 @@ public class FileDownloaderImpl implements FileDownloader { indicator.setText2(IdeBundle.message("progress.locate.file.text", fileDescription.getPresentableFileName())); final String path = FileUtil.toSystemDependentName(StringUtil.trimStart(url, LIB_SCHEMA)); final File file = PathManager.findFileInLibDirectory(path); - downloadedFiles.add(Pair.create(fileDescription, file)); + downloadedFiles.add(Pair.create(file, fileDescription)); } else if (url.startsWith(LocalFileSystem.PROTOCOL_PREFIX)) { String path = FileUtil.toSystemDependentName(StringUtil.trimStart(url, LocalFileSystem.PROTOCOL_PREFIX)); File file = new File(path); if (file.exists()) { - downloadedFiles.add(Pair.create(fileDescription, file)); + downloadedFiles.add(Pair.create(file, fileDescription)); } } else { @@ -290,7 +299,7 @@ public class FileDownloaderImpl implements FileDownloader { NetUtils.copyStreamContent(indicator, input, output, size); deleteFile = false; - downloadedFiles.add(Pair.create(fileDescription, tempFile)); + downloadedFiles.add(Pair.create(tempFile, fileDescription)); } finally { if (input != null) { diff --git a/platform/lang-impl/src/com/intellij/util/download/impl/FileSetVersionsFetcherBase.java b/platform/lang-impl/src/com/intellij/util/download/impl/FileSetVersionsFetcherBase.java index cef0acf2dba3..d839a93f61db 100644 --- a/platform/lang-impl/src/com/intellij/util/download/impl/FileSetVersionsFetcherBase.java +++ b/platform/lang-impl/src/com/intellij/util/download/impl/FileSetVersionsFetcherBase.java @@ -21,7 +21,6 @@ import com.intellij.facet.frameworks.beans.ArtifactItem; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.download.DownloadableFileDescription; -import com.intellij.util.download.DownloadableFileService; import com.intellij.util.download.DownloadableFileSetDescription; import com.intellij.util.download.DownloadableFileSetVersions; import org.jetbrains.annotations.NotNull; @@ -36,7 +35,7 @@ import java.util.List; /** * @author nik */ -public abstract class FileSetVersionsFetcherBase implements DownloadableFileSetVersions { +public abstract class FileSetVersionsFetcherBase implements DownloadableFileSetVersions { private static final Comparator VERSIONS_COMPARATOR = new Comparator() { @Override public int compare(DownloadableFileSetDescription o1, DownloadableFileSetDescription o2) { @@ -52,7 +51,7 @@ public abstract class FileSetVersionsFetcherBase callback) { + public void fetchVersions(@NotNull final FileSetVersionsCallback callback) { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @Override public void run() { @@ -63,10 +62,10 @@ public abstract class FileSetVersionsFetcherBase result = new ArrayList(); + final List result = new ArrayList(); for (Artifact version : versions) { final ArtifactItem[] items = version.getItems(); - final List files = new ArrayList(); + final List files = new ArrayList(); for (ArtifactItem item : items) { String url = item.getUrl(); final String prefix = version.getUrlPrefix(); @@ -75,13 +74,11 @@ public abstract class FileSetVersionsFetcherBase files); + @NotNull + protected static String prependPrefix(@NotNull String url, @Nullable String prefix) { + if (!url.startsWith("http://") && prefix != null) { + url = prefix + url; + } + return url; + } + + protected abstract F createFileDescription(ArtifactItem item, String url, @Nullable String prefix); + + protected abstract FS createVersion(Artifact version, List files); } diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/CheckboxAction.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/CheckboxAction.java index 90f095f062ee..0af1dca66998 100644 --- a/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/CheckboxAction.java +++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/CheckboxAction.java @@ -45,6 +45,7 @@ public abstract class CheckboxAction extends ToggleAction implements CustomCompo public JComponent createCustomComponent(Presentation presentation) { myCheckBox = new JCheckBox(presentation.getText()); + myCheckBox.setOpaque(false); myCheckBox.setToolTipText(presentation.getDescription()); myCheckBox.setMnemonic(presentation.getMnemonic()); myCheckBox.setDisplayedMnemonicIndex(presentation.getDisplayedMnemonicIndex()); diff --git a/platform/platform-api/src/com/intellij/openapi/editor/EditorModificationUtil.java b/platform/platform-api/src/com/intellij/openapi/editor/EditorModificationUtil.java index e80150193419..a2bd9b91ca8e 100644 --- a/platform/platform-api/src/com/intellij/openapi/editor/EditorModificationUtil.java +++ b/platform/platform-api/src/com/intellij/openapi/editor/EditorModificationUtil.java @@ -44,12 +44,9 @@ public class EditorModificationUtil { int selectionStart = selectionModel.getSelectionStart(); int selectionEnd = selectionModel.getSelectionEnd(); - final CaretModel caretModel = editor.getCaretModel(); - final VisualPosition position = caretModel.getVisualPosition(); - caretModel.moveToOffset(selectionStart); + editor.getCaretModel().moveToOffset(selectionStart); selectionModel.removeSelection(); editor.getDocument().deleteString(selectionStart, selectionEnd); - caretModel.moveToVisualPosition(position); // Try to preserve visual caret position editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } diff --git a/platform/platform-api/src/com/intellij/openapi/ui/Messages.java b/platform/platform-api/src/com/intellij/openapi/ui/Messages.java index 839eea53bd76..d013f7f08d6b 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/Messages.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/Messages.java @@ -169,6 +169,12 @@ public class Messages { } } + /** + * Use this method only if you do not know project or component + * + * @see #showDialog(Project, String, String, String[], int, Icon, DialogWrapper.DoNotAskOption) + * @see #showDialog(Component, String, String, String[], int, Icon) + */ public static int showDialog(String message, String title, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); @@ -195,6 +201,12 @@ public class Messages { return showDialog(message, title, options, defaultOptionIndex, defaultOptionIndex, icon, doNotAskOption); } + /** + * Use this method only if you do not know project or component + * + * @see #showDialog(Project, String, String, String[], int, Icon) + * @see #showDialog(Component, String, String, String[], int, Icon) + */ public static int showDialog(String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon) { return showDialog(message, title, options, defaultOptionIndex, icon, null); } @@ -269,6 +281,12 @@ public class Messages { } + /** + * Use this method only if you do not know project or component + * + * @see #showYesNoDialog(Project, ...) + * @see #showYesNoDialog(Component, ...) + */ public static int showYesNoDialog(String message, String title, String yesText, String noText, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (canShowMacSheetPanel()) { @@ -282,8 +300,8 @@ public class Messages { * Use this method only if you do not know project or component * * @return 0 if user pressed "Yes" and returns 1 if user pressed "No" button. - * @see #showYesNoDialog(Project, String, String, Icon) - * @see #showYesNoDialog(Component, String, String, Icon) + * @see #showYesNoDialog(Project, String, String, String, String, Icon) + * @see #showYesNoDialog(Component, ...) */ public static int showYesNoDialog(String message, String title, String yesText, String noText, @Nullable Icon icon) { return showYesNoDialog(message, title, yesText, noText, icon, null); @@ -349,10 +367,22 @@ public class Messages { return showOkCancelDialog(message, title, OK_BUTTON, CANCEL_BUTTON, icon, null); } + /** + * Use this method only if you do not know project or component + * + * @see #showOkCancelDialog(Project, String, String, String, String, Icon) + * @see #showOkCancelDialog(Component, String, String, String, String, Icon) + */ public static int showOkCancelDialog(String message, String title, String okText, String cancelText, Icon icon) { return showOkCancelDialog(message, title, okText, cancelText, icon, null); } + /** + * Use this method only if you do not know project or component + * + * @see #showOkCancelDialog(Project, String, String, String, String, Icon, DialogWrapper.DoNotAskOption) + * @see #showOkCancelDialog(Component, String, String, String, String, Icon) + */ public static int showOkCancelDialog(String message, String title, String okText, String cancelText, Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, okText, cancelText, null, doNotAskOption); @@ -495,6 +525,12 @@ public class Messages { } + /** + * Use this method only if you do not know project or component + * + * @see #showYesNoCancelDialog(Project, String, String, String, String, String, Icon) + * @see #showYesNoCancelDialog(Component, String, String, String, String, String, Icon) + */ public static int showYesNoCancelDialog(String message, String title, String yes, String no, String cancel, Icon icon, DialogWrapper.DoNotAskOption doNotAskOption) { if (canShowMacSheetPanel()) { @@ -504,6 +540,12 @@ public class Messages { return showDialog(message, title, new String[]{yes, no, cancel}, 0, icon, doNotAskOption); } + /** + * Use this method only if you do not know project or component + * + * @see #showYesNoCancelDialog(Project, String, String, String, String, String, Icon) + * @see #showYesNoCancelDialog(Component, String, String, String, String, String, Icon) + */ public static int showYesNoCancelDialog(String message, String title, String yes, String no, String cancel, Icon icon) { return showYesNoCancelDialog(message, title, yes, no, cancel, icon, null); } @@ -741,6 +783,11 @@ public class Messages { /** * Shows dialog with given message and title, information icon {@link #getInformationIcon()} and OK button + * + * Use this method only if you do not know project or component + * + * @see #showInputDialog(Project, String, String, Icon, String, InputValidator) + * @see #showInputDialog(Component, String, String, Icon, String, InputValidator) */ public static void showInfoMessage(String message, String title) { if (canShowMacSheetPanel()) { diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryHelper.java b/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryHelper.java index 2afa077e15ab..8c88722e06c2 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryHelper.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryHelper.java @@ -41,6 +41,7 @@ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; +import java.util.zip.GZIPInputStream; /** * Created by IntelliJ IDEA. @@ -56,44 +57,55 @@ public class RepositoryHelper { @NonNls public static final String extPluginsFile = "availables.xml"; public static ArrayList process(@Nullable ProgressIndicator indicator) throws IOException, ParserConfigurationException, SAXException { - ArrayList plugins = null; - try { - BuildNumber buildNumber = ApplicationInfo.getInstance().getBuild(); - @NonNls String url = getListUrl() + "?build=" + buildNumber.asString(); + BuildNumber buildNumber = ApplicationInfo.getInstance().getBuild(); + @NonNls String url = getListUrl() + "?build=" + buildNumber.asString(); + if (indicator != null) { + indicator.setText2(IdeBundle.message("progress.connecting.to.plugin.manager", getRepositoryHost())); + } + + HttpConfigurable.getInstance().setAuthenticator(); + + HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection(); + connection.setRequestProperty("Accept-Encoding", "gzip"); + + if (indicator != null) { + indicator.setText2(IdeBundle.message("progress.waiting.for.reply.from.plugin.manager", getRepositoryHost())); + } + + connection.connect(); + + try { if (indicator != null) { - indicator.setText2(IdeBundle.message("progress.connecting.to.plugin.manager", getRepositoryHost())); + indicator.checkCanceled(); } - HttpConfigurable.getInstance().prepareURL(getRepositoryHost()); -// if( !pi.isCanceled() ) - { - RepositoryContentHandler handler = new RepositoryContentHandler(); - HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection(); + + String encoding = connection.getContentEncoding(); + + InputStream is = connection.getInputStream(); + + try { + if ("gzip".equalsIgnoreCase(encoding)) { + is = new GZIPInputStream(is); + } if (indicator != null) { - indicator.setText2(IdeBundle.message("progress.waiting.for.reply.from.plugin.manager", getRepositoryHost())); + indicator.setText2(IdeBundle.message("progress.downloading.list.of.plugins")); } - InputStream is = getConnectionInputStream(connection); - if (is != null) { - if (indicator != null) { - indicator.setText2(IdeBundle.message("progress.downloading.list.of.plugins")); - } - readPluginsStream( is, handler, indicator, extPluginsFile); + RepositoryContentHandler handler = new RepositoryContentHandler(); - plugins = handler.getPluginsList(); - } + readPluginsStream( is, handler, indicator, extPluginsFile); + + return handler.getPluginsList(); + } + finally { + is.close(); } } - catch (ProcessCanceledException e) { - throw e; + finally { + connection.disconnect(); } - catch (RuntimeException e) { - e.printStackTrace(); - if (e.getCause() == null || !(e.getCause() instanceof InterruptedException)) { - } - } - return plugins; } private static void setLabelText(@Nullable final JLabel label, final String message) { @@ -105,16 +117,6 @@ public class RepositoryHelper { }); } - - public static InputStream getConnectionInputStream(URLConnection connection) { - try { - return connection.getInputStream(); - } - catch (IOException e) { - return null; - } - } - private static File createLocalPluginsDescriptions(final String file) throws IOException { File basePath = new File(PathManager.getPluginsPath()); basePath.mkdirs(); diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceByDocument.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceByDocument.java index 7aad7fd2998c..4c5ceab88a6e 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceByDocument.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceByDocument.java @@ -28,11 +28,13 @@ public class DocumentReferenceByDocument implements DocumentReference { myDocument = document; } + @Override @NotNull public Document getDocument() { return myDocument; } + @Override @Nullable public VirtualFile getFile() { return null; diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceByVirtualFile.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceByVirtualFile.java index dc2c2643658f..271bf8f84c12 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceByVirtualFile.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceByVirtualFile.java @@ -29,12 +29,14 @@ public class DocumentReferenceByVirtualFile implements DocumentReference { myFile = file; } + @Override @Nullable public Document getDocument() { assert myFile.isValid() : "should not be called on references to deleted file: " + myFile; return FileDocumentManager.getInstance().getDocument(myFile); } + @Override @NotNull public VirtualFile getFile() { return myFile; diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceManagerImpl.java index 620e57792cbc..a53830f241b7 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentReferenceManagerImpl.java @@ -41,14 +41,16 @@ public class DocumentReferenceManagerImpl extends DocumentReferenceManager imple private static final Key> DELETED_FILES = Key.create(DocumentReferenceManagerImpl.class.getName() + ".DELETED_FILES"); private final Map, DocumentReference> myDocToRef = new WeakValueHashMap, DocumentReference>(); - private final Map myFileToRef = new WeakValueHashMap(); + private final Map, DocumentReference> myFileToRef = new WeakValueHashMap, DocumentReference>(); private final Map myDeletedFilePathToRef = new WeakValueHashMap(); + @Override @NotNull public String getComponentName() { return getClass().getSimpleName(); } + @Override public void initComponent() { VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileAdapter() { @Override @@ -56,7 +58,7 @@ public class DocumentReferenceManagerImpl extends DocumentReferenceManager imple VirtualFile f = event.getFile(); DocumentReference ref = myDeletedFilePathToRef.remove(new FilePath(f.getUrl())); if (ref != null) { - myFileToRef.put(f, ref); + myFileToRef.put(new WeakReferenceWithEquals(f), ref); ((DocumentReferenceByVirtualFile)ref).update(f); } } @@ -73,8 +75,10 @@ public class DocumentReferenceManagerImpl extends DocumentReferenceManager imple List files = f.getUserData(DELETED_FILES); f.putUserData(DELETED_FILES, null); + assert files != null; for (VirtualFile each : files) { - DocumentReference ref = myFileToRef.remove(each); + Reference r = new WeakReferenceWithEquals(each); + DocumentReference ref = myFileToRef.remove(r); if (ref != null) { myDeletedFilePathToRef.put(new FilePath(each.getUrl()), ref); } @@ -83,7 +87,7 @@ public class DocumentReferenceManagerImpl extends DocumentReferenceManager imple }); } - private List collectDeletedFiles(VirtualFile f, List files) { + private static List collectDeletedFiles(VirtualFile f, List files) { if (!(f instanceof NewVirtualFile)) return files; if (!f.isDirectory()) { @@ -97,6 +101,7 @@ public class DocumentReferenceManagerImpl extends DocumentReferenceManager imple return files; } + @Override public void disposeComponent() { } @@ -110,19 +115,7 @@ public class DocumentReferenceManagerImpl extends DocumentReferenceManager imple } private DocumentReference doCreate(@NotNull final Document document) { - final int hashCode = document.hashCode(); - Reference reference = new WeakReference(document) { - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object obj) { - Document mydoc = get(); - return mydoc != null && obj instanceof Reference && ((Reference)obj).get() == mydoc; - } - }; + Reference reference = new WeakReferenceWithEquals(document); DocumentReference result = myDocToRef.get(reference); if (result == null) { result = new DocumentReferenceByDocument(document); @@ -137,15 +130,36 @@ public class DocumentReferenceManagerImpl extends DocumentReferenceManager imple assertInDispatchThread(); assert file.isValid() : "file is invalid: " + file; - DocumentReference result = myFileToRef.get(file); + WeakReferenceWithEquals ref = new WeakReferenceWithEquals(file); + DocumentReference result = myFileToRef.get(ref); if (result == null) { result = new DocumentReferenceByVirtualFile(file); - myFileToRef.put(file, result); + myFileToRef.put(ref, result); } return result; } - private void assertInDispatchThread() { + private static void assertInDispatchThread() { ApplicationManager.getApplication().assertIsDispatchThread(); } + + private static class WeakReferenceWithEquals extends WeakReference { + final int hashCode; + + public WeakReferenceWithEquals(@NotNull T document) { + super(document); + hashCode = document.hashCode(); + } + + @Override + public int hashCode() { + return hashCode; + } + + @Override + public boolean equals(Object obj) { + T doc = get(); + return doc != null && obj instanceof Reference && ((Reference)obj).get() == doc; + } + } } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteLineAction.java b/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteLineAction.java index 4f29a9e4e2e2..ddf21185c915 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteLineAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteLineAction.java @@ -53,8 +53,10 @@ public class DeleteLineAction extends TextComponentEditorAction { document.deleteString(lineStartOffset, nextLineStartOffset); return; } + final VisualPosition position = editor.getCaretModel().getVisualPosition(); editor.getSelectionModel().selectLineAtCaret(); EditorModificationUtil.deleteSelectedText(editor); + editor.getCaretModel().moveToVisualPosition(position); } } } diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java index 2585c25ab461..03791c9477d5 100644 --- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorHistoryManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -105,10 +105,17 @@ public final class EditorHistoryManager extends AbstractProjectComponent impleme return "editorHistoryManager"; } + private void fileOpenedImpl(@NotNull final VirtualFile file) { + fileOpenedImpl(file, null, null); + } + /** * Makes file most recent one */ - private void fileOpenedImpl(@NotNull final VirtualFile file){ + private void fileOpenedImpl(@NotNull final VirtualFile file, + @Nullable final FileEditor fallbackEditor, + @Nullable FileEditorProvider fallbackProvider) + { ApplicationManager.getApplication().assertIsDispatchThread(); // don't add files that cannot be found via VFM (light & etc.) if (VirtualFileManager.getInstance().findFileByUrl(file.getUrl()) == null) return; @@ -116,12 +123,21 @@ public final class EditorHistoryManager extends AbstractProjectComponent impleme final FileEditorManagerEx editorManager = FileEditorManagerEx.getInstanceEx(myProject); final Pair editorsWithProviders = editorManager.getEditorsWithProviders(file); - final FileEditor[] editors = editorsWithProviders.getFirst(); - final FileEditorProvider[] oldProviders = editorsWithProviders.getSecond(); + FileEditor[] editors = editorsWithProviders.getFirst(); + FileEditorProvider[] oldProviders = editorsWithProviders.getSecond(); + if (editors.length <= 0 && fallbackEditor != null) { + editors = new FileEditor[] { fallbackEditor }; + } + if (oldProviders.length <= 0 && fallbackProvider != null) { + oldProviders = new FileEditorProvider[] { fallbackProvider }; + } if (editors.length <= 0) { LOG.error("No editors for file " + file.getPresentableUrl()); } - final FileEditor selectedEditor = editorManager.getSelectedEditor(file); + FileEditor selectedEditor = editorManager.getSelectedEditor(file); + if (selectedEditor == null) { + selectedEditor = fallbackEditor; + } LOG.assertTrue(selectedEditor != null); final int selectedProviderIndex = ArrayUtil.find(editors, selectedEditor); LOG.assertTrue(selectedProviderIndex != -1); @@ -131,7 +147,7 @@ public final class EditorHistoryManager extends AbstractProjectComponent impleme myEntriesList.remove(entry); myEntriesList.add(entry); } - else{ + else { final FileEditorState[] states=new FileEditorState[editors.length]; final FileEditorProvider[] providers=new FileEditorProvider[editors.length]; for (int i = states.length - 1; i >= 0; i--) { @@ -176,7 +192,7 @@ public final class EditorHistoryManager extends AbstractProjectComponent impleme // Size of entry list can be less than number of opened editors (some entries can be removed) if (file.isValid()) { // the file could have been deleted, so the isValid() check is essential - fileOpenedImpl(file); + fileOpenedImpl(file, fallbackEditor, fallbackProvider); } return; } diff --git a/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java b/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java index 2ef7edd40c51..2ae74ead6838 100644 --- a/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java +++ b/platform/platform-impl/src/com/intellij/platform/NewDirectoryProjectDialog.java @@ -15,6 +15,7 @@ */ package com.intellij.platform; +import com.google.common.collect.Lists; import com.intellij.facet.ui.FacetEditorValidator; import com.intellij.facet.ui.FacetValidatorsManager; import com.intellij.facet.ui.ValidationResult; @@ -27,13 +28,16 @@ import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.ui.DocumentAdapter; import com.intellij.util.SystemProperties; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.DocumentEvent; +import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; +import java.util.List; /** * @author yole @@ -53,6 +57,7 @@ public class NewDirectoryProjectDialog extends DialogWrapper { private JPanel myPlaceHolder; private static final Object EMPTY_PROJECT_GENERATOR = new Object(); + private final DirectoryProjectGenerator myGeneratorBeforeSeparator; protected NewDirectoryProjectDialog(Project project) { super(project, true); @@ -66,26 +71,38 @@ public class NewDirectoryProjectDialog extends DialogWrapper { final DirectoryProjectGenerator[] generators = getGenerators(); if (generators.length == 0) { myProjectTypePanel.setVisible(false); + myGeneratorBeforeSeparator = null; } else { DefaultComboBoxModel model = new DefaultComboBoxModel(); model.addElement(getEmptyProjectGenerator()); + List primaryGenerators = Lists.newArrayList(); + List otherGenerators = Lists.newArrayList(); for (DirectoryProjectGenerator generator : generators) { + boolean primary = true; + if (generator instanceof WebProjectGenerator) { + primary = ((WebProjectGenerator) generator).isPrimaryGenerator(); + } + if (primary) { + primaryGenerators.add(generator); + } else { + otherGenerators.add(generator); + } + } + if (!primaryGenerators.isEmpty() && !otherGenerators.isEmpty()) { + myGeneratorBeforeSeparator = primaryGenerators.get(primaryGenerators.size() - 1); + } + else { + myGeneratorBeforeSeparator = null; + } + for (DirectoryProjectGenerator generator : primaryGenerators) { + model.addElement(generator); + } + for (DirectoryProjectGenerator generator : otherGenerators) { model.addElement(generator); } myProjectTypeComboBox.setModel(model); - myProjectTypeComboBox.setRenderer(new ListCellRendererWrapper(myProjectTypeComboBox.getRenderer()) { - @Override - public void customize(final JList list, final Object value, final int index, final boolean selected, final boolean cellHasFocus) { - if (value == null) return; - if (value == EMPTY_PROJECT_GENERATOR) { - setText("Empty project"); - } - else { - setText(((DirectoryProjectGenerator)value).getName()); - } - } - }); + myProjectTypeComboBox.setRenderer(createProjectTypeListCellRenderer(myProjectTypeComboBox.getRenderer())); } registerValidators(new FacetValidatorsManager() { @@ -98,6 +115,46 @@ public class NewDirectoryProjectDialog extends DialogWrapper { }); } + @NotNull + private ListCellRenderer createProjectTypeListCellRenderer(@NotNull final ListCellRenderer originalRenderer) { + ListCellRenderer intermediate = myGeneratorBeforeSeparator == null ? originalRenderer : new ListCellRenderer() { + + private final JSeparator mySeparator = new JSeparator(SwingConstants.HORIZONTAL); + private final JPanel myComponentWithSeparator = new JPanel(new BorderLayout(0, 0)); + + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component original = originalRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (index != -1 && value == myGeneratorBeforeSeparator + && value instanceof DirectoryProjectGenerator && original instanceof JLabel) { + myComponentWithSeparator.removeAll(); + + JLabel label = (JLabel) original; + label.setText(((DirectoryProjectGenerator) value).getName()); + myComponentWithSeparator.add(label, BorderLayout.CENTER); + myComponentWithSeparator.add(mySeparator, BorderLayout.SOUTH); + + myComponentWithSeparator.revalidate(); + myComponentWithSeparator.repaint(); + return myComponentWithSeparator; + } + return original; + } + }; + return new ListCellRendererWrapper(intermediate) { + @Override + public void customize(final JList list, final Object value, final int index, final boolean selected, final boolean cellHasFocus) { + if (value == null) return; + if (value == EMPTY_PROJECT_GENERATOR) { + setText("Empty project"); + } + else { + setText(((DirectoryProjectGenerator)value).getName()); + } + } + }; + } + protected Object getEmptyProjectGenerator() { return EMPTY_PROJECT_GENERATOR; } diff --git a/platform/platform-impl/src/com/intellij/platform/WebProjectGenerator.java b/platform/platform-impl/src/com/intellij/platform/WebProjectGenerator.java index 9812f4724b3e..d11569f29274 100644 --- a/platform/platform-impl/src/com/intellij/platform/WebProjectGenerator.java +++ b/platform/platform-impl/src/com/intellij/platform/WebProjectGenerator.java @@ -68,6 +68,10 @@ public abstract class WebProjectGenerator implements DirectoryProjectGenerato @NotNull public abstract GeneratorPeer createPeer(); + public boolean isPrimaryGenerator() { + return true; + } + public interface GeneratorPeer { @NotNull JComponent getComponent(); diff --git a/platform/platform-resources-en/src/messages/CodeInsightBundle.properties b/platform/platform-resources-en/src/messages/CodeInsightBundle.properties index 701d9da115bc..ffe3d28e1c8b 100644 --- a/platform/platform-resources-en/src/messages/CodeInsightBundle.properties +++ b/platform/platform-resources-en/src/messages/CodeInsightBundle.properties @@ -31,8 +31,8 @@ dialog.reformat.files.reformat.selected.files.label=Reformat selected files? command.name.typing=Typing dialog.import.on.paste.title=Select Classes to Import dialog.import.on.paste.title2=Select Elements to Import -dialog.paste.on.import.text=The code fragment which you have pasted uses classes that are not accessible by imports in the new context.
Select classes that you want to import to the new file. -dialog.paste.on.import.text2=The code fragment which you have pasted uses elements that are not accessible by imports in the new context.
Select elements that you want to import to the new file. +dialog.paste.on.import.text=The code fragment which you have pasted uses classes that are not accessible by imports in the new context.
Select classes that you want to import to the new file. +dialog.paste.on.import.text2=The code fragment which you have pasted uses elements that are not accessible by imports in the new context.
Select elements that you want to import to the new file. paste.data.flavor.folding=FoldingData paste.dataflavor.referencedata=ReferenceData generate.constructor.fields.chooser.title=Choose Fields to Initialize by Constructor diff --git a/platform/platform-resources-en/src/messages/InspectionsBundle.properties b/platform/platform-resources-en/src/messages/InspectionsBundle.properties index 934b3cf961f7..779ff6223685 100644 --- a/platform/platform-resources-en/src/messages/InspectionsBundle.properties +++ b/platform/platform-resources-en/src/messages/InspectionsBundle.properties @@ -274,6 +274,7 @@ inspection.problem.resolution=Problem resolution inspection.quickfix.assert.family=Assert inspection.assert.quickfix=Assert ''{0}'' inspection.surround.if.quickfix=Surround with ''if ({0} != null)'' +inspection.replace.ternary.quickfix=Replace with ''{0} != null ?:'' inspection.surround.if.family=Surround with if inspection.dependency.configure.button.text=Configure dependency rules diff --git a/platform/platform-resources-en/src/messages/RefactoringBundle.properties b/platform/platform-resources-en/src/messages/RefactoringBundle.properties index c2c7a42de06f..2cb2d9ae1727 100644 --- a/platform/platform-resources-en/src/messages/RefactoringBundle.properties +++ b/platform/platform-resources-en/src/messages/RefactoringBundle.properties @@ -133,7 +133,13 @@ no.field.name.specified=No field name specified field.exists=The field with the name {0}\nalready exists in class ''{1}''.\nContinue? choose.destination.class=Choose Destination Class replace.write.access.occurrences=Rep&lace write access occurrences + +# introduce variable introduce.variable.title=Introduce Variable +refactoring.introduce.context.error=Cannot perform refactoring in this context +refactoring.introduceVariable=Introduce Variable refactoring +refactoring.introduce.selection.error=Cannot perform refactoring using selected element(s) + variable.of.type=Variable of &type: convert.to.instance.method.title=Convert To Instance Method convertToInstanceMethod.method.is.not.static=Cannot perform the refactoring\nMethod {0} is not static. @@ -170,6 +176,7 @@ class.is.interface={0} is an interface. class.does.not.have.base.classes.or.interfaces=Class {0} does not have base classes or interfaces. inline.title=Inline introduce.constant.title=Introduce Constant +introduce.selection.error=Cannot perform refactoring using selected element(s) selected.expression.cannot.be.a.constant.initializer=Selected expression cannot be a constant initializer. variable.does.not.have.an.initializer=Variable {0} does not have an initializer. initializer.for.variable.cannot.be.a.constant.initializer=Initializer for variable {0} cannot be a constant initializer. diff --git a/platform/platform-resources-en/src/messages/UsageView.properties b/platform/platform-resources-en/src/messages/UsageView.properties index 3ed9c19827bd..a8333adb3c88 100644 --- a/platform/platform-resources-en/src/messages/UsageView.properties +++ b/platform/platform-resources-en/src/messages/UsageView.properties @@ -53,6 +53,7 @@ usage.target.package.in.directory={0} (in {1}) usage.target.exception=Exception usage.type.new=New instance creation usage.type.new.inner=New inner class instance creation +usage.type.new.anonymous=New anonymous inheritor creation usage.type.new.array=New array creation usage.type.annotation=Annotation usage.type.type.parameter=Type parameter diff --git a/platform/platform-resources-en/src/misc/registry.properties b/platform/platform-resources-en/src/misc/registry.properties index 4a852935c5fa..3b2ec5dbe19b 100644 --- a/platform/platform-resources-en/src/misc/registry.properties +++ b/platform/platform-resources-en/src/misc/registry.properties @@ -139,13 +139,13 @@ compiler.out-of-process.build.enabled.description=Enable out-of-process compilat compiler.out-of-process.as-server=false compiler.out-of-process.as-server.description=Use implementation of out-of-process build as server process -compiler.process.heap.size=600 +compiler.process.heap.size=700 compiler.process.heap.size.description=Heap size value in MB for the build process compiler.process.32bit.vm.on.mac=true compiler.process.32bit.vm.on.mac.description=Force -d32 VM option on Mac (recommended for faster startup and lower memory footprint) -compiler.process.vm.options=-ea +compiler.process.vm.options= compiler.process.vm.options.description=Additional options for compile server's VM compiler.process.use.memory.temp.cache=true diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModifiableModelCommitter.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModifiableModelCommitter.java index 1ba173dfe919..9d0d766d6b9a 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModifiableModelCommitter.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/ModifiableModelCommitter.java @@ -34,8 +34,7 @@ import java.util.*; public class ModifiableModelCommitter { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.module.impl.ModifiableModelCommitter"); - public static void multiCommit(ModifiableRootModel[] rootModels, - ModifiableModuleModel moduleModel) { + public static void multiCommit(ModifiableRootModel[] rootModels, ModifiableModuleModel moduleModel) { ApplicationManager.getApplication().assertWriteAccessAllowed(); final List modelsToCommit = getSortedChangedModels(rootModels, moduleModel); diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/SourceFolderImpl.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/SourceFolderImpl.java index 049e7048b875..824a71d36ab4 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/SourceFolderImpl.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/SourceFolderImpl.java @@ -100,7 +100,9 @@ public class SourceFolderImpl extends ContentFolderBaseImpl implements SourceFol @Override public ContentFolder cloneFolder(ContentEntry contentEntry) { - return new SourceFolderImpl(this, (ContentEntryImpl) contentEntry); + assert !((ContentEntryImpl)contentEntry).isDisposed() : "target entry already disposed: " + contentEntry; + assert !isDisposed() : "Already disposed: " + this; + return new SourceFolderImpl(this, (ContentEntryImpl)contentEntry); } @Override diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/libraries/JarDirectories.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/libraries/JarDirectories.java index e52129a9915b..b9334dd6685f 100644 --- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/libraries/JarDirectories.java +++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/libraries/JarDirectories.java @@ -33,8 +33,8 @@ import java.util.List; * @author nik */ public class JarDirectories implements JDOMExternalizable { - private MultiMap myDirectories = new MultiMap(); - private MultiMap myRecursivelyIncluded = new MultiMap(); + private final MultiMap myDirectories = new MultiMap(); + private final MultiMap myRecursivelyIncluded = new MultiMap(); @NonNls private static final String JAR_DIRECTORY_ELEMENT = "jarDirectory"; @NonNls private static final String URL_ATTR = "url"; diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java index 95f715bd7854..22bcbf4715be 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java @@ -43,7 +43,7 @@ import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VfsUtil; +import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.util.*; @@ -72,10 +72,12 @@ import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.jar.JarFile; +import static org.junit.Assert.assertNotNull; /** * @author yole */ +@SuppressWarnings("UseOfSystemOutOrSystemErr") public class PlatformTestUtil { public static final boolean COVERAGE_ENABLED_BUILD = "true".equals(System.getProperty("idea.coverage.enabled.build")); public static final CvsVirtualFileFilter CVS_FILE_FILTER = new CvsVirtualFileFilter(); @@ -616,11 +618,15 @@ public class PlatformTestUtil { public static void assertDirectoriesEqual(VirtualFile dirAfter, VirtualFile dirBefore, @Nullable VirtualFileFilter fileFilter) throws IOException { FileDocumentManager.getInstance().saveAllDocuments(); + + dirAfter.getChildren(); + dirAfter.refresh(false, false); VirtualFile[] childrenAfter = dirAfter.getChildren(); if (dirAfter.isInLocalFileSystem()) { File[] ioAfter = new File(dirAfter.getPath()).listFiles(); shallowCompare(childrenAfter, ioAfter); } + VirtualFile[] childrenBefore = dirBefore.getChildren(); if (dirBefore.isInLocalFileSystem()) { File[] ioBefore = new File(dirBefore.getPath()).listFiles(); @@ -672,16 +678,27 @@ public class PlatformTestUtil { public static void assertFilesEqual(VirtualFile fileAfter, VirtualFile fileBefore) throws IOException { try { - assertJarFilesEqual(VfsUtil.virtualToIoFile(fileAfter), VfsUtil.virtualToIoFile(fileBefore)); + assertJarFilesEqual(VfsUtilCore.virtualToIoFile(fileAfter), VfsUtilCore.virtualToIoFile(fileBefore)); } catch (IOException e) { FileDocumentManager manager = FileDocumentManager.getInstance(); + Document docBefore = manager.getDocument(fileBefore); boolean canLoadBeforeText = !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN; - String textB = docBefore == null ? !canLoadBeforeText ? null : LoadTextUtil.getTextByBinaryPresentation(fileBefore.contentsToByteArray(false), fileBefore).toString() : docBefore.getText(); + String textB = docBefore != null + ? docBefore.getText() + : !canLoadBeforeText + ? null + : LoadTextUtil.getTextByBinaryPresentation(fileBefore.contentsToByteArray(false), fileBefore).toString(); + Document docAfter = manager.getDocument(fileAfter); boolean canLoadAfterText = !fileBefore.getFileType().isBinary() || fileBefore.getFileType() == FileTypes.UNKNOWN; - String textA = docAfter == null ? !canLoadAfterText ? null : LoadTextUtil.getTextByBinaryPresentation(fileAfter.contentsToByteArray(false), fileAfter).toString() : docAfter.getText(); + String textA = docAfter != null + ? docAfter.getText() + : !canLoadAfterText + ? null + : LoadTextUtil.getTextByBinaryPresentation(fileAfter.contentsToByteArray(false), fileAfter).toString(); + if (textA != null && textB != null) { Assert.assertEquals(fileAfter.getPath(), textA, textB); } @@ -692,28 +709,30 @@ public class PlatformTestUtil { } public static void assertJarFilesEqual(File file1, File file2) throws IOException { - JarFile jarFile1 = null; - JarFile jarFile2 = null; final File tempDirectory1; final File tempDirectory2; + + final JarFile jarFile1 = new JarFile(file1); try { - jarFile2 = new JarFile(file2); - jarFile1 = new JarFile(file1); - tempDirectory1 = PlatformTestCase.createTempDir("tmp1"); - tempDirectory2 = PlatformTestCase.createTempDir("tmp2"); - ZipUtil.extract(jarFile1, tempDirectory1, CVS_FILE_FILTER); - ZipUtil.extract(jarFile2, tempDirectory2, CVS_FILE_FILTER); - } - finally { - if (jarFile1 != null) { - jarFile1.close(); + final JarFile jarFile2 = new JarFile(file2); + try { + tempDirectory1 = PlatformTestCase.createTempDir("tmp1"); + tempDirectory2 = PlatformTestCase.createTempDir("tmp2"); + ZipUtil.extract(jarFile1, tempDirectory1, CVS_FILE_FILTER); + ZipUtil.extract(jarFile2, tempDirectory2, CVS_FILE_FILTER); } - if (jarFile2 != null) { + finally { jarFile2.close(); } } + finally { + jarFile1.close(); + } + final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1); + assertNotNull(tempDirectory1.toString(), dirAfter); final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2); + assertNotNull(tempDirectory2.toString(), dirBefore); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { diff --git a/platform/usageView/src/com/intellij/usages/impl/rules/UsageType.java b/platform/usageView/src/com/intellij/usages/impl/rules/UsageType.java index e0f402a1141a..43905dd67b2e 100644 --- a/platform/usageView/src/com/intellij/usages/impl/rules/UsageType.java +++ b/platform/usageView/src/com/intellij/usages/impl/rules/UsageType.java @@ -32,6 +32,7 @@ public final class UsageType { public static final UsageType CLASS_METHOD_RETURN_TYPE = new UsageType(UsageViewBundle.message("usage.type.return")); public static final UsageType CLASS_NEW_OPERATOR = new UsageType(UsageViewBundle.message("usage.type.new")); public static final UsageType CLASS_INNER_NEW_OPERATOR = new UsageType(UsageViewBundle.message("usage.type.new.inner")); + public static final UsageType CLASS_ANONYMOUS_NEW_OPERATOR = new UsageType(UsageViewBundle.message("usage.type.new.anonymous")); public static final UsageType CLASS_NEW_ARRAY = new UsageType(UsageViewBundle.message("usage.type.new.array")); public static final UsageType ANNOTATION = new UsageType(UsageViewBundle.message("usage.type.annotation")); public static final UsageType TYPE_PARAMETER = new UsageType(UsageViewBundle.message("usage.type.type.parameter")); diff --git a/platform/usageView/src/com/intellij/usages/impl/rules/UsageTypeGroupingRule.java b/platform/usageView/src/com/intellij/usages/impl/rules/UsageTypeGroupingRule.java index 30c69dd1c1d4..d0ca1fc0052a 100644 --- a/platform/usageView/src/com/intellij/usages/impl/rules/UsageTypeGroupingRule.java +++ b/platform/usageView/src/com/intellij/usages/impl/rules/UsageTypeGroupingRule.java @@ -59,7 +59,7 @@ public class UsageTypeGroupingRule implements UsageGroupingRuleEx { } @Nullable - private static UsageType getUsageType(PsiElement element, UsageTarget[] targets) { + private static UsageType getUsageType(PsiElement element, @NotNull UsageTarget[] targets) { if (element == null) return null; if (PsiTreeUtil.getParentOfType(element, PsiComment.class, false) != null) { return UsageType.COMMENT_USAGE; } diff --git a/platform/usageView/src/com/intellij/usages/impl/rules/UsageTypeProviderEx.java b/platform/usageView/src/com/intellij/usages/impl/rules/UsageTypeProviderEx.java index f31c33801f0c..011a65c95514 100644 --- a/platform/usageView/src/com/intellij/usages/impl/rules/UsageTypeProviderEx.java +++ b/platform/usageView/src/com/intellij/usages/impl/rules/UsageTypeProviderEx.java @@ -17,6 +17,7 @@ package com.intellij.usages.impl.rules; import com.intellij.psi.PsiElement; import com.intellij.usages.UsageTarget; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** @@ -25,5 +26,5 @@ import org.jetbrains.annotations.Nullable; public interface UsageTypeProviderEx extends UsageTypeProvider { @Nullable UsageType - getUsageType(PsiElement element, UsageTarget[] targets); + getUsageType(PsiElement element, @NotNull UsageTarget[] targets); } diff --git a/platform/util-rt/src/com/intellij/execution/rmi/RemoteDeadHand.java b/platform/util-rt/src/com/intellij/execution/rmi/RemoteDeadHand.java new file mode 100644 index 000000000000..5f2dc0e8a160 --- /dev/null +++ b/platform/util-rt/src/com/intellij/execution/rmi/RemoteDeadHand.java @@ -0,0 +1,66 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.execution.rmi; + +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.registry.LocateRegistry; +import java.rmi.registry.Registry; +import java.rmi.server.UnicastRemoteObject; + +/** + * @author gregsh + */ +public interface RemoteDeadHand extends Remote { + + String BINDING_NAME = "_DEAD_HAND_"; + + /** + * @return time in milliseconds to wait till the next ping. + * Negative return value means "terminate", 0 means "live forever" and should be avoided. + */ + long ping(String id) throws RemoteException; + + class TwoMinutesTurkish extends RemoteObject implements RemoteDeadHand { + + private static final TwoMinutesTurkish ourCook = new TwoMinutesTurkish(); + private static final Remote ourHand; + private static long ourAskedThatManyTimes; + + static { + Remote remote; + try { + remote = UnicastRemoteObject.exportObject(ourCook, 0); + } + catch (RemoteException e) { + throw new IllegalStateException(e); + } + ourHand = remote; + } + + @Override + public long ping(String id) throws RemoteException { + //noinspection AssignmentToStaticFieldFromInstanceMethod + ourAskedThatManyTimes ++; + return 2 * 60 * 1000L; + } + + public static void startCooking(String host, int port) throws Exception { + final Registry registry = LocateRegistry.getRegistry(host, port); + registry.bind(RemoteDeadHand.BINDING_NAME, ourHand); + } + } +} diff --git a/platform/util-rt/src/com/intellij/execution/rmi/RemoteServer.java b/platform/util-rt/src/com/intellij/execution/rmi/RemoteServer.java index 9e846ea83a56..3e3084ff2f3f 100644 --- a/platform/util-rt/src/com/intellij/execution/rmi/RemoteServer.java +++ b/platform/util-rt/src/com/intellij/execution/rmi/RemoteServer.java @@ -59,11 +59,19 @@ public class RemoteServer { final String name = remote.getClass().getSimpleName() + Integer.toHexString(stub.hashCode()); registry.bind(name, stub); - System.out.println("Port/ID: " + port + "/" + name); + String id = port + "/" + name; + System.out.println("Port/ID: " + id); + long waitTime = 2 * 60 * 1000L; Object lock = new Object(); - synchronized (lock) { - lock.wait(); + //noinspection InfiniteLoopStatement + while (true) { + //noinspection SynchronizationOnLocalVariableOrMethodParameter + synchronized (lock) { + lock.wait(waitTime); + } + RemoteDeadHand deadHand = (RemoteDeadHand)registry.lookup(RemoteDeadHand.BINDING_NAME); + waitTime = deadHand.ping(id); } } catch (Throwable e) { diff --git a/platform/util/src/com/intellij/util/messages/impl/MessageBusConnectionImpl.java b/platform/util/src/com/intellij/util/messages/impl/MessageBusConnectionImpl.java index 2f0ec718bf36..ecbc66b22b8c 100644 --- a/platform/util/src/com/intellij/util/messages/impl/MessageBusConnectionImpl.java +++ b/platform/util/src/com/intellij/util/messages/impl/MessageBusConnectionImpl.java @@ -34,12 +34,7 @@ public class MessageBusConnectionImpl implements MessageBusConnection { private static final Logger LOG = Logger.getInstance("#com.intellij.util.messages.impl.MessageBusConnectionImpl"); private final MessageBusImpl myBus; - private final ThreadLocal> myPendingMessages = new ThreadLocal>() { - @Override - protected Queue initialValue() { - return new ConcurrentLinkedQueue(); - } - }; + private final ThreadLocal> myPendingMessages = new QueueThreadLocal(); private MessageHandler myDefaultHandler; private final Map mySubscriptions = new HashMap(); @@ -129,4 +124,11 @@ public class MessageBusConnectionImpl implements MessageBusConnection { public String toString() { return mySubscriptions.keySet().toString(); } + + private static class QueueThreadLocal extends ThreadLocal> { + @Override + protected Queue initialValue() { + return new ConcurrentLinkedQueue(); + } + } } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangeListManagerImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangeListManagerImpl.java index c307fae99d32..0345b050d32b 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangeListManagerImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangeListManagerImpl.java @@ -649,7 +649,7 @@ public class ChangeListManagerImpl extends ChangeListManagerEx implements Projec if (myUpdater.isStopped()) throw new DisposedException(); } - static boolean isUnder(final Change change, final VcsDirtyScope scope) { + public static boolean isUnder(final Change change, final VcsDirtyScope scope) { final ContentRevision before = change.getBeforeRevision(); final ContentRevision after = change.getAfterRevision(); return before != null && scope.belongsTo(before.getFile()) || after != null && scope.belongsTo(after.getFile()); diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/LocalChangeListImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/LocalChangeListImpl.java index 4a4fd2b9fb06..b1de7e38155d 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/LocalChangeListImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/LocalChangeListImpl.java @@ -1,4 +1,3 @@ - package com.intellij.openapi.vcs.changes; import com.intellij.lifecycle.PeriodicalTasksCloser; @@ -146,7 +145,11 @@ public class LocalChangeListImpl extends LocalChangeList { if (scope == null || before != null && scope.belongsTo(before.getFile()) || after != null && scope.belongsTo(after.getFile()) || isIgnoredChange(oldBoy, fileIndex)) { result.add(oldBoy); - removeChange(oldBoy); + if (ChangeListManagerImpl.DEBUG) { + System.out.println("LocalChangeListImpl.startProcessingChanges, remove old change: this = " + this + ", change = " + oldBoy); + } + myChanges.remove(oldBoy); + myReadChangesCache = null; } } return result; diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesComparator.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesComparator.java index 2ad27429687c..1a7bf9b55f51 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesComparator.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesComparator.java @@ -15,6 +15,9 @@ */ package com.intellij.openapi.vcs.changes.ui; +import com.intellij.openapi.util.SystemInfo; +import com.intellij.openapi.util.io.FileUtilRt; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ChangesUtil; @@ -42,15 +45,16 @@ public class ChangesComparator implements Comparator { final FilePath filePath1 = ChangesUtil.getFilePath(o1); final FilePath filePath2 = ChangesUtil.getFilePath(o2); if (myTreeCompare) { - final FilePath parentPath1 = filePath1.getParentPath(); - final FilePath parentPath2 = filePath2.getParentPath(); - if (parentPath1 != null && parentPath2 != null && parentPath1.isUnder(parentPath2, true)) { - return -1; + final String path1 = FileUtilRt.toSystemIndependentName(filePath1.getPath()); + final String path2 = FileUtilRt.toSystemIndependentName(filePath2.getPath()); + final int lastSlash1 = path1.lastIndexOf('/'); + final String parentPath1 = lastSlash1 >= 0 && !filePath1.isDirectory() ? path1.substring(0, lastSlash1) : path1; + final int lastSlash2 = path2.lastIndexOf('/'); + final String parentPath2 = lastSlash2 >= 0 && !filePath2.isDirectory() ? path2.substring(0, lastSlash2) : path2; + final int compare = StringUtil.compare(parentPath1, parentPath2, !SystemInfo.isFileSystemCaseSensitive); + if (compare != 0) { + return compare; } - if (parentPath2 != null && parentPath1 != null && parentPath2.isUnder(parentPath1, true)) { - return 1; - } - return filePath1.getPath().compareToIgnoreCase(filePath2.getPath()); } return filePath1.getName().compareToIgnoreCase(filePath2.getName()); } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ProjectLevelVcsManagerImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ProjectLevelVcsManagerImpl.java index 1e0b36dfadcf..de48dedf80fe 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ProjectLevelVcsManagerImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ProjectLevelVcsManagerImpl.java @@ -548,7 +548,9 @@ public void addMessageToConsoleWindow(final String message, final TextAttributes public VcsShowConfirmationOption getStandardConfirmation(@NotNull VcsConfiguration.StandardConfirmation option, AbstractVcs vcs) { final VcsShowConfirmationOptionImpl result = getConfirmation(option); - result.addApplicableVcs(vcs); + if (vcs != null) { + result.addApplicableVcs(vcs); + } return result; } diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/BreakpointItem.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/BreakpointItem.java index 3dbc5b0541a4..82abf3ad6522 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/BreakpointItem.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/BreakpointItem.java @@ -15,8 +15,12 @@ */ package com.intellij.xdebugger.breakpoints.ui; +import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.colors.EditorColorsManager; +import com.intellij.openapi.editor.impl.DocumentMarkupModel; +import com.intellij.openapi.editor.markup.MarkupModel; +import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; @@ -46,7 +50,28 @@ public abstract class BreakpointItem implements ItemWrapper { public abstract void setEnabled(boolean state); protected void showInEditor(DetailView panel, VirtualFile virtualFile, int line) { - panel.navigateInPreviewEditor(virtualFile, new LogicalPosition(line, 0), null); + TextAttributes attributes = + EditorColorsManager.getInstance().getGlobalScheme().getAttributes(DebuggerColors.BREAKPOINT_ATTRIBUTES); + + panel.navigateInPreviewEditor(virtualFile, new LogicalPosition(line, 0), attributes); + + TextAttributes softerAttributes = attributes.clone(); + softerAttributes.setBackgroundColor(ColorUtil.softer(softerAttributes.getBackgroundColor())); + + final Editor editor = panel.getEditor(); + final MarkupModel editorModel = editor.getMarkupModel(); + final MarkupModel documentModel = + DocumentMarkupModel.forDocument(editor.getDocument(), editor.getProject(), false); + + for (RangeHighlighter highlighter : documentModel.getAllHighlighters()) { + if (highlighter.getUserData(DebuggerColors.BREAKPOINT_HIGHLIGHTER_KEY) == Boolean.TRUE) { + final int line1 = editor.offsetToLogicalPosition(highlighter.getStartOffset()).line; + if (line1 != line) { + editorModel.addLineHighlighter(line1, + DebuggerColors.BREAKPOINT_HIGHLIGHTER_LAYER + 1, softerAttributes); + } + } + } } @Override diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroup.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroup.java index ffa9c892f209..03d32f3fd8db 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroup.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroup.java @@ -36,11 +36,6 @@ public abstract class XBreakpointGroup implements Comparable { return getName().compareTo(o.getName()); } - @Override - public boolean equals(Object obj) { - return obj instanceof XBreakpointGroup && compareTo((XBreakpointGroup)obj) == 0; - } - @Override public int hashCode() { return getName().hashCode(); diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingByTypeRule.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingByTypeRule.java index ec64306ea25a..d843b375833c 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingByTypeRule.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingByTypeRule.java @@ -33,6 +33,11 @@ public class XBreakpointGroupingByTypeRule extends XBreakpointGroupingRule groups) { if (b instanceof XBreakpoint) { diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingRule.java b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingRule.java index b152b869d3e7..477dc9ce697c 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingRule.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/breakpoints/ui/XBreakpointGroupingRule.java @@ -29,6 +29,10 @@ public abstract class XBreakpointGroupingRule { private final String myId; private final String myPresentableName; + public boolean isAlwaysEnabled() { + return false; + } + protected XBreakpointGroupingRule(final @NotNull @NonNls String id, final @NonNls @Nls String presentableName) { myId = id; myPresentableName = presentableName; diff --git a/platform/xdebugger-api/src/com/intellij/xdebugger/ui/DebuggerColors.java b/platform/xdebugger-api/src/com/intellij/xdebugger/ui/DebuggerColors.java index 5c34a979f4f4..3ef5a2e88ee4 100644 --- a/platform/xdebugger-api/src/com/intellij/xdebugger/ui/DebuggerColors.java +++ b/platform/xdebugger-api/src/com/intellij/xdebugger/ui/DebuggerColors.java @@ -22,6 +22,7 @@ package com.intellij.xdebugger.ui; import com.intellij.openapi.editor.colors.ColorKey; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.markup.HighlighterLayer; +import com.intellij.openapi.util.Key; import java.awt.*; @@ -31,5 +32,7 @@ public interface DebuggerColors { ColorKey RECURSIVE_CALL_ATTRIBUTES = ColorKey.createColorKey("RECURSIVE_CALL_ATTRIBUTES", new Color(255, 255, 215)); int BREAKPOINT_HIGHLIGHTER_LAYER = HighlighterLayer.SYNTAX + 1; + + Key BREAKPOINT_HIGHLIGHTER_KEY = Key.create("BREAKPOINT_HIGHLIGHTER_KEY"); int EXECUTION_LINE_HIGHLIGHTERLAYER = HighlighterLayer.SELECTION - 1; } diff --git a/platform/xdebugger-api/xdebugger-api.iml b/platform/xdebugger-api/xdebugger-api.iml index 5e37d936a983..9b0209ca69aa 100644 --- a/platform/xdebugger-api/xdebugger-api.iml +++ b/platform/xdebugger-api/xdebugger-api.iml @@ -8,6 +8,7 @@ + diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointPanelProvider.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointPanelProvider.java index 5529ba0af3d4..02ca25d275f0 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointPanelProvider.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XBreakpointPanelProvider.java @@ -50,7 +50,7 @@ public class XBreakpointPanelProvider extends BreakpointPanelProvider myListeners = new CopyOnWriteArrayList(); @Override - public void provideBreakpointsGroupingRules(Collection rules) { + public void createBreakpointsGroupingRules(Collection rules) { rules.add(new XBreakpointGroupingByTypeRule()); rules.add(new XBreakpointFileGroupingRule()); } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointImpl.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointImpl.java index dfe161a81663..0528037a01af 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointImpl.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/XLineBreakpointImpl.java @@ -87,6 +87,7 @@ public class XLineBreakpointImpl

extends XBreak if (highlighter != null) { updateIcon(); highlighter.setGutterIconRenderer(createGutterIconRenderer()); + highlighter.putUserData(DebuggerColors.BREAKPOINT_HIGHLIGHTER_KEY, Boolean.TRUE); } myHighlighter = highlighter; } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointItemsTree.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointItemsTree.java index 7392d9e24881..13fe05927c62 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointItemsTree.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointItemsTree.java @@ -87,23 +87,52 @@ public class BreakpointItemsTree extends CheckboxTree { } //TreeUtil.sort(myRoot, myComparator); ((DefaultTreeModel)getModel()).nodeStructureChanged(myRoot); - expandPath(new TreePath(myRoot)); state.applyTo(this, myRoot); + TreeUtil.expandAll(this); } @NotNull private CheckedTreeNode getParentNode(final BreakpointItem breakpoint) { CheckedTreeNode parent = myRoot; + XBreakpointGroup parentGroup = null; for (int i = 0; i < myGroupingRules.size(); i++) { - XBreakpointGroup group = getGroup(breakpoint.getBreakpoint(), myGroupingRules.get(i)); + XBreakpointGroup group = getGroup(parentGroup, breakpoint, myGroupingRules.get(i)); if (group != null) { parent = getOrCreateGroupNode(parent, group, i); + parentGroup = group; } } return parent; } + @Nullable + private XBreakpointGroup getGroup(XBreakpointGroup parentGroup, final BreakpointItem breakpoint, final XBreakpointGroupingRule groupingRule) { + //noinspection unchecked + Collection groups = myGroups.get(groupingRule); + if (groups == null) { + groups = Collections.emptyList(); + } + + XBreakpointGroup group = groupingRule.getGroup(breakpoint.getBreakpoint(), filterByParent(parentGroup, groups)); + if (group != null) { + myGroups.put(groupingRule, group); + } + return group; + } + + private Collection filterByParent(XBreakpointGroup parentGroup, Collection groups) { + Collection filtered = new ArrayList(); + for (XBreakpointGroup group : groups) { + TreeNode parentNode = myGroupNodes.get(group).getParent(); + BreakpointsGroupNode parent = parentNode instanceof BreakpointsGroupNode ? (BreakpointsGroupNode)parentNode : null; + if ((parentGroup == null && parentNode == myRoot) || (parent != null && parent.getGroup() == parentGroup)) { + filtered.add(group); + } + } + return filtered; + } + private BreakpointsGroupNode getOrCreateGroupNode(CheckedTreeNode parent, final G group, final int level) { //noinspection unchecked @@ -123,20 +152,6 @@ public class BreakpointItemsTree extends CheckboxTree { } } - @Nullable - private XBreakpointGroup getGroup(final Object breakpoint, final XBreakpointGroupingRule groupingRule) { - //noinspection unchecked - Collection groups = myGroups.get(groupingRule); - if (groups == null) { - groups = Collections.emptyList(); - } - XBreakpointGroup group = groupingRule.getGroup(breakpoint, groups); - if (group != null) { - myGroups.put(groupingRule, group); - } - return group; - } - @Override protected void onNodeStateChanged(final CheckedTreeNode node) { if (node instanceof BreakpointItemNode) { @@ -144,7 +159,7 @@ public class BreakpointItemsTree extends CheckboxTree { } } - public void setGroupingRules(List groupingRules) { + public void setGroupingRules(Collection groupingRules) { List selectedBreakpoints = getSelectedBreakpoints(); List allBreakpoints = new ArrayList(myNodes.keySet()); diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointMasterDetailPopupBuilder.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointMasterDetailPopupBuilder.java new file mode 100644 index 000000000000..fce09fb83953 --- /dev/null +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointMasterDetailPopupBuilder.java @@ -0,0 +1,265 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.xdebugger.impl.breakpoints.ui; + +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.DefaultActionGroup; +import com.intellij.openapi.actionSystem.ex.CheckboxAction; +import com.intellij.openapi.editor.colors.EditorColorsManager; +import com.intellij.openapi.editor.colors.EditorColorsScheme; +import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager; +import com.intellij.openapi.editor.colors.impl.EditorColorsSchemeImpl; +import com.intellij.openapi.editor.markup.EffectType; +import com.intellij.openapi.editor.markup.TextAttributes; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.popup.JBPopup; +import com.intellij.openapi.ui.popup.JBPopupFactory; +import com.intellij.openapi.ui.popup.JBPopupListener; +import com.intellij.openapi.ui.popup.LightweightWindowEvent; +import com.intellij.ui.IdeBorderFactory; +import com.intellij.ui.popup.util.MasterDetailPopupBuilder; +import com.intellij.util.IconUtil; +import com.intellij.util.PlatformIcons; +import com.intellij.util.containers.HashSet; +import com.intellij.xdebugger.breakpoints.ui.BreakpointItem; +import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroupingRule; +import com.intellij.xdebugger.ui.DebuggerColors; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.KeyEvent; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +public class BreakpointMasterDetailPopupBuilder { + + private Project myProject; + private MasterDetailPopupBuilder myPopupBuilder; + private Collection myBreakpointsPanelProviders; + private BreakpointItemsTree myTree; + private final List myRulesAvailable = new ArrayList(); + + private final Set myRulesEnabled = new HashSet(); + + @Nullable private Object myInitialBreakpoint; + + public void setInitialBreakpoint(@Nullable Object initialBreakpoint) { + myInitialBreakpoint = initialBreakpoint; + } + + public BreakpointMasterDetailPopupBuilder(Project project) { + myProject = project; + } + + + public JBPopup createPopup() { + myPopupBuilder = new MasterDetailPopupBuilder(myProject); + + for (BreakpointPanelProvider provider : myBreakpointsPanelProviders) { + provider.createBreakpointsGroupingRules(myRulesAvailable); + } + + for (XBreakpointGroupingRule rule : myRulesAvailable) { + if (rule.isAlwaysEnabled()) { + myRulesEnabled.add(rule); + } + } + + DefaultActionGroup actions = createActions(); + + + myTree = BreakpointItemsTree.createTree(getEnabledRulesList()); + + final ArrayList breakpoints = collectItems(); + myTree.buildTree(breakpoints); + + + final BreakpointPanelProvider.BreakpointsListener listener = new BreakpointPanelProvider.BreakpointsListener() { + @Override + public void breakpointsChanged() { + myTree.buildTree(collectItems()); + } + }; + + for (BreakpointPanelProvider provider : myBreakpointsPanelProviders) { + provider.addListener(listener, myProject); + } + + final JBPopup popup = myPopupBuilder. + setActionsGroup(actions). + setTree(myTree). + setDelegate(new MasterDetailPopupBuilder.Delegate() { + @Override + public String getTitle() { + return "Breakpoints"; + } + + @Override + public void handleMnemonic(KeyEvent e, Project project, JBPopup popup) { + //To change body of implemented methods use File | Settings | File Templates. + } + + public JComponent createAccessoryView(Project project) { + return new JCheckBox(); + } + + @Override + public Object[] getSelectedItemsInTree() { + final List res = myTree.getSelectedBreakpoints(); + return res.toArray(new Object[res.size()]); + } + }).setCloseOnEnter(false).createMasterDetailPopup(); + + myTree.setBorder(IdeBorderFactory.createBorder()); + + myTree.setDelegate(new BreakpointItemsTree.BreakpointItemsTreeDelegate() { + @Override + public void execute(BreakpointItem item) { + item.execute(myProject, popup); + } + }); + + initSelection(breakpoints); + + popup.addListener(new JBPopupListener() { + @Override + public void beforeShown(LightweightWindowEvent event) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void onClosed(LightweightWindowEvent event) { + for (BreakpointPanelProvider provider : myBreakpointsPanelProviders) { + provider.removeListener(listener); + } + } + }); + + return popup; + } + + void initSelection(ArrayList breakpoints) { + boolean found = false; + for (BreakpointItem breakpoint : breakpoints) { + if (breakpoint.getBreakpoint() == myInitialBreakpoint) { + myTree.selectBreakpointItem(breakpoint); + found = true; + break; + } + } + + if (!found && !breakpoints.isEmpty()) { + myTree.selectBreakpointItem(breakpoints.get(0)); + } + } + + EditorColorsScheme createScheme() { + final EditorColorsScheme scheme = + new EditorColorsSchemeImpl(EditorColorsManager.getInstance().getGlobalScheme(), DefaultColorSchemesManager.getInstance()); + scheme.setName("abc"); + scheme + .setAttributes(DebuggerColors.BREAKPOINT_ATTRIBUTES, new TextAttributes(Color.black, Color.CYAN, null, EffectType.BOXED, Font.BOLD)); + return scheme; + } + + DefaultActionGroup createActions() { + DefaultActionGroup actions = new DefaultActionGroup(); + final DefaultActionGroup breakpointTypes = new DefaultActionGroup(); + for (BreakpointPanelProvider provider : myBreakpointsPanelProviders) { + breakpointTypes.addAll(provider.getAddBreakpointActions(myProject)); + } + actions.add(new AnAction("Add Breakpoint", null, IconUtil.getAddIcon()) { + @Override + public void actionPerformed(AnActionEvent e) { + + JBPopupFactory.getInstance() + .createActionGroupPopup(null, breakpointTypes, e.getDataContext(), JBPopupFactory.ActionSelectionAid.NUMBERING, false) + .showUnderneathOf(myPopupBuilder.getActionToolbar().getComponent()); + } + }); + actions.add(new AnAction("Remove Breakpoint", null, PlatformIcons.DELETE_ICON) { + @Override + public void update(AnActionEvent e) { + e.getPresentation().setEnabled(MasterDetailPopupBuilder.allowedToRemoveItems(myPopupBuilder.getSelectedItems())); + } + + @Override + public void actionPerformed(AnActionEvent e) { + myPopupBuilder.removeSelectedItems(myProject); + } + }); + + for (XBreakpointGroupingRule rule : myRulesAvailable) { + if (!rule.isAlwaysEnabled()) { + actions.add(new ToggleBreakpointGroupingRuleEnabledAction(rule)); + } + } + + return actions; + } + + ArrayList collectItems() { + ArrayList items = new ArrayList(); + for (BreakpointPanelProvider panelProvider : myBreakpointsPanelProviders) { + panelProvider.provideBreakpointItems(myProject, items); + } + return items; + } + + public void setBreakpointsPanelProviders(Collection breakpointsPanelProviders) { + myBreakpointsPanelProviders = breakpointsPanelProviders; + } + + private class ToggleBreakpointGroupingRuleEnabledAction extends CheckboxAction { + private XBreakpointGroupingRule myRule; + + public ToggleBreakpointGroupingRuleEnabledAction(XBreakpointGroupingRule rule) { + super(rule.getPresentableName()); + myRule = rule; + getTemplatePresentation().setText(rule.getPresentableName()); + } + + @Override + public boolean isSelected(AnActionEvent e) { + return myRulesEnabled.contains(myRule); + } + + @Override + public void setSelected(AnActionEvent e, boolean state) { + if (state) { + myRulesEnabled.add(myRule); + } + else { + myRulesEnabled.remove(myRule); + } + myTree.setGroupingRules(getEnabledRulesList()); + } + } + + private List getEnabledRulesList() { + List result = new ArrayList(); + for (XBreakpointGroupingRule rule : myRulesAvailable) { + if (myRulesEnabled.contains(rule)) { + result.add(rule); + } + } + return result; + } +} diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointPanelProvider.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointPanelProvider.java index 954a4ddcb564..fc6fdd750d69 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointPanelProvider.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointPanelProvider.java @@ -32,7 +32,7 @@ import java.util.Collection; */ public abstract class BreakpointPanelProvider { - public abstract void provideBreakpointsGroupingRules(Collection rules); + public abstract void createBreakpointsGroupingRules(Collection rules); public interface BreakpointsListener { void breakpointsChanged(); diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsMasterDetailPopupFactory.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsMasterDetailPopupFactory.java index e8ddf05d8e57..e86c9cfbfa8c 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsMasterDetailPopupFactory.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsMasterDetailPopupFactory.java @@ -15,48 +15,25 @@ */ package com.intellij.xdebugger.impl.breakpoints.ui; -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.editor.colors.EditorColorsManager; -import com.intellij.openapi.editor.colors.EditorColorsScheme; -import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager; -import com.intellij.openapi.editor.colors.impl.EditorColorsSchemeImpl; -import com.intellij.openapi.editor.markup.EffectType; -import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopup; -import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.JBPopupListener; import com.intellij.openapi.ui.popup.LightweightWindowEvent; -import com.intellij.ui.IdeBorderFactory; -import com.intellij.ui.popup.util.MasterDetailPopupBuilder; -import com.intellij.util.IconUtil; -import com.intellij.util.PlatformIcons; -import com.intellij.xdebugger.breakpoints.ui.BreakpointItem; -import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroupingRule; import com.intellij.xdebugger.impl.DebuggerSupport; -import com.intellij.xdebugger.ui.DebuggerColors; import org.jetbrains.annotations.Nullable; -import javax.swing.*; -import java.awt.*; -import java.awt.event.KeyEvent; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.List; -/** - * Created with IntelliJ IDEA. - * User: zajac - * Date: 5/9/12 - * Time: 3:11 AM - * To change this template use File | Settings | File Templates. - */ public class BreakpointsMasterDetailPopupFactory { private final List myBreakpointPanelProviders; private Project myProject; + private Balloon myBalloonToHide; public BreakpointsMasterDetailPopupFactory(Project project) { myProject = project; @@ -72,153 +49,30 @@ public class BreakpointsMasterDetailPopupFactory { }); } + public void setBalloonToHide(Balloon balloonToHide) { + myBalloonToHide = balloonToHide; + } + public static BreakpointsMasterDetailPopupFactory getInstance(Project project) { return ServiceManager.getService(project, BreakpointsMasterDetailPopupFactory.class); } public JBPopup createPopup(@Nullable Object initialBreakpoint) { - - MasterDetailPopupBuilder popupBuilder = new MasterDetailPopupBuilder(myProject); - - DefaultActionGroup actions = getActions(popupBuilder); - - final Collection rules = new ArrayList(); - - for (BreakpointPanelProvider provider : myBreakpointPanelProviders) { - provider.provideBreakpointsGroupingRules(rules); - } - - final BreakpointItemsTree tree = BreakpointItemsTree.createTree(rules); - - final ArrayList breakpoints = collectItems(); - tree.buildTree(breakpoints); - - - - final BreakpointPanelProvider.BreakpointsListener listener = new BreakpointPanelProvider.BreakpointsListener() { - @Override - public void breakpointsChanged() { - tree.buildTree(collectItems()); - } - }; - - for (BreakpointPanelProvider provider : myBreakpointPanelProviders) { - provider.addListener(listener, myProject); - } - - final JBPopup popup = popupBuilder. - setActionsGroup(actions). - setTree(tree). - setDelegate(new MasterDetailPopupBuilder.Delegate() { - @Override - public String getTitle() { - return "Breakpoints"; - } - - @Override - public void handleMnemonic(KeyEvent e, Project project, JBPopup popup) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public JComponent createAccessoryView(Project project) { - return new JCheckBox(); - } - - @Override - public Object[] getSelectedItemsInTree() { - final List res = tree.getSelectedBreakpoints(); - return res.toArray(new Object[res.size()]); - } - }).setCloseOnEnter(false).createMasterDetailPopup(); - - tree.setBorder(IdeBorderFactory.createBorder()); - - popupBuilder.getDetailView().setScheme(createScheme()); - - tree.setDelegate(new BreakpointItemsTree.BreakpointItemsTreeDelegate() { - @Override - public void execute(BreakpointItem item) { - item.execute(myProject, popup); - } - }); - - initSelection(initialBreakpoint, tree, breakpoints); - + BreakpointMasterDetailPopupBuilder builder = new BreakpointMasterDetailPopupBuilder(myProject); + builder.setInitialBreakpoint(initialBreakpoint); + builder.setBreakpointsPanelProviders(myBreakpointPanelProviders); + final JBPopup popup = builder.createPopup(); popup.addListener(new JBPopupListener() { @Override public void beforeShown(LightweightWindowEvent event) { - //To change body of implemented methods use File | Settings | File Templates. + myBalloonToHide.hide(); } @Override public void onClosed(LightweightWindowEvent event) { - for (BreakpointPanelProvider provider : myBreakpointPanelProviders) { - provider.removeListener(listener); - } + //To change body of implemented methods use File | Settings | File Templates. } }); - return popup; } - - private void initSelection(Object initialBreakpoint, BreakpointItemsTree tree, ArrayList breakpoints) { - boolean found = false; - for (BreakpointItem breakpoint : breakpoints) { - if (breakpoint.getBreakpoint() == initialBreakpoint) { - tree.selectBreakpointItem(breakpoint); - found = true; - break; - } - } - - if (!found && !breakpoints.isEmpty()) { - tree.selectBreakpointItem(breakpoints.get(0)); - } - } - - private EditorColorsScheme createScheme() { - final EditorColorsScheme scheme = - new EditorColorsSchemeImpl(EditorColorsManager.getInstance().getGlobalScheme(), DefaultColorSchemesManager.getInstance()); - scheme.setName("abc"); - scheme.setAttributes(DebuggerColors.BREAKPOINT_ATTRIBUTES, new TextAttributes(Color.black, Color.CYAN, null, EffectType.BOXED, Font.BOLD)); - return scheme; - } - - private DefaultActionGroup getActions(final MasterDetailPopupBuilder builder) { - DefaultActionGroup actions = new DefaultActionGroup(); - final DefaultActionGroup breakpointTypes = new DefaultActionGroup(); - for (BreakpointPanelProvider provider : myBreakpointPanelProviders) { - breakpointTypes.addAll(provider.getAddBreakpointActions(myProject)); - } - actions.add(new AnAction("Add Breakpoint", null, IconUtil.getAddIcon()) { - @Override - public void actionPerformed(AnActionEvent e) { - - JBPopupFactory.getInstance() - .createActionGroupPopup(null, breakpointTypes, e.getDataContext(), JBPopupFactory.ActionSelectionAid.NUMBERING, false) - .showUnderneathOf(builder.getActionToolbar().getComponent()); - } - }); - actions.add(new AnAction("Remove Breakpoint", null, PlatformIcons.DELETE_ICON) { - @Override - public void update(AnActionEvent e) { - e.getPresentation().setEnabled(MasterDetailPopupBuilder.allowedToRemoveItems(builder.getSelectedItems())); - } - - @Override - public void actionPerformed(AnActionEvent e) { - builder.removeSelectedItems(myProject); - } - }); - - return actions; - } - - private ArrayList collectItems() { - ArrayList items = new ArrayList(); - for (BreakpointPanelProvider panelProvider : myBreakpointPanelProviders) { - panelProvider.provideBreakpointItems(myProject, items); - } - return items; - } } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/BreakpointEditor.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/BreakpointEditor.java index a7ff22409457..58812079ef1a 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/BreakpointEditor.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/BreakpointEditor.java @@ -40,7 +40,7 @@ public class BreakpointEditor { } private void createUIComponents() { - myShowMoreOptionsLink = new LinkLabel("More Options", null, new LinkListener() { + myShowMoreOptionsLink = new LinkLabel("View Breakpoints...", null, new LinkListener() { @Override public void linkSelected(LinkLabel aSource, Object aLinkData) { if (myDelegate != null) { diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/DebuggerUIUtil.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/DebuggerUIUtil.java index 11b58784b313..76a869e6813e 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/DebuggerUIUtil.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/DebuggerUIUtil.java @@ -24,6 +24,7 @@ import com.intellij.openapi.ui.popup.*; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.DimensionService; +import com.intellij.openapi.util.Ref; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.WindowManager; import com.intellij.ui.ScrollPaneFactory; @@ -33,6 +34,7 @@ import com.intellij.xdebugger.breakpoints.XBreakpoint; import com.intellij.xdebugger.breakpoints.XBreakpointListener; import com.intellij.xdebugger.breakpoints.XBreakpointManager; import com.intellij.xdebugger.frame.XFullValueEvaluator; +import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointsMasterDetailPopupFactory; import com.intellij.xdebugger.impl.breakpoints.ui.XLightBreakpointPropertiesPanel; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -168,17 +170,44 @@ public class DebuggerUIUtil { final XLightBreakpointPropertiesPanel propertiesPanel = new XLightBreakpointPropertiesPanel(project, breakpointManager, breakpoint, showAllOptions); + + final Ref balloonRef = Ref.create(null); + final Ref isLoading = Ref.create(Boolean.FALSE); + + propertiesPanel.setDelegate(new XLightBreakpointPropertiesPanel.Delegate() { + @Override + public void showMoreOptions() { + if (!isLoading.get()) { + propertiesPanel.saveProperties(); + } + if (!balloonRef.isNull()) { + balloonRef.get().hide(); + } + showXBreakpointEditorBalloon(project, point, component, true, breakpoint); + } + }); + + + isLoading.set(Boolean.TRUE); propertiesPanel.loadProperties(); + isLoading.set(Boolean.FALSE); + final JComponent mainPanel = propertiesPanel.getMainPanel(); - final Runnable showMoreOptions = new Runnable() { + final Runnable viewBreakpoints = new Runnable() { @Override public void run() { propertiesPanel.saveProperties(); - showXBreakpointEditorBalloon(project, point, component, true, breakpoint); + //showXBreakpointEditorBalloon(project, point, component, true, breakpoint); + BreakpointsMasterDetailPopupFactory. + getInstance(project).createPopup(breakpoint).showCenteredInCurrentWindow(project); } }; - final Balloon balloon = showBreakpointEditor(mainPanel, breakpoint.getType().getDisplayText(breakpoint), point, component, propertiesPanel.showMoreOptions() ? showMoreOptions : null); + + final Balloon balloon = showBreakpointEditor(project, mainPanel, breakpoint.getType().getDisplayText(breakpoint), point, component, viewBreakpoints); + balloonRef.set(balloon); + + final XBreakpointListener> breakpointListener = new XBreakpointListener>() { @Override public void breakpointAdded(@NotNull XBreakpoint breakpoint1) { @@ -208,14 +237,7 @@ public class DebuggerUIUtil { } }); - propertiesPanel.setDelegate(new XLightBreakpointPropertiesPanel.Delegate() { - @Override - public void showMoreOptions() { - propertiesPanel.saveProperties(); - balloon.hide(); - showXBreakpointEditorBalloon(project, point, component, true, breakpoint); - } - }); + if (point == null) { @@ -233,14 +255,14 @@ public class DebuggerUIUtil { }); } - public static Balloon showBreakpointEditor(final JComponent mainPanel, + public static Balloon showBreakpointEditor(Project project, final JComponent mainPanel, final String displayName, final Point whereToShow, final JComponent component, @Nullable final Runnable showMoreOptions) { final BreakpointEditor editor = new BreakpointEditor(); editor.setPropertiesPanel(mainPanel); - editor.setShowMoreOptionsLink(showMoreOptions != null); + editor.setShowMoreOptionsLink(true); final Balloon balloon = JBPopupFactory.getInstance() .createDialogBalloonBuilder(editor.getMainPanel(), null) @@ -250,6 +272,7 @@ public class DebuggerUIUtil { .setBlockClicksThroughBalloon(true) .createBalloon(); + editor.setDelegate(new BreakpointEditor.Delegate() { @Override public void done() { @@ -271,6 +294,8 @@ public class DebuggerUIUtil { balloon.show(new RelativePoint(component, whereToShow), Balloon.Position.below); } + BreakpointsMasterDetailPopupFactory.getInstance(project).setBalloonToHide(balloon); + return balloon; } diff --git a/plugins/android-designer/src/META-INF/plugin.xml b/plugins/android-designer/src/META-INF/plugin.xml index e14f2545aae2..79c31c21e215 100644 --- a/plugins/android-designer/src/META-INF/plugin.xml +++ b/plugins/android-designer/src/META-INF/plugin.xml @@ -11,7 +11,8 @@ com.intellij.ui-designer-new - + + formats) { @@ -177,8 +177,12 @@ public class ResourceEditor extends PropertyEditor { myRootComponent = rootComponent; JTextField text = getComboText(); text.setText((String)value); - if (inplaceContext != null && inplaceContext.isStartChar()) { - text.setText(inplaceContext.getText(text.getText())); + if (inplaceContext != null) { + text.setColumns(0); + + if (inplaceContext.isStartChar()) { + text.setText(inplaceContext.getText(text.getText())); + } } return myEditor; } diff --git a/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidApkBuilder.java b/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidApkBuilder.java index 4fa0175b31a0..70d180c8bec5 100644 --- a/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidApkBuilder.java +++ b/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidApkBuilder.java @@ -139,7 +139,7 @@ public class AndroidApkBuilder { } final String zipAlignPath = sdkPath + File.separator + AndroidCommonUtils.toolPath(SdkConstants.FN_ZIPALIGN); boolean withAlignment = new File(zipAlignPath).exists(); - String unalignedApk = finalApk + UNALIGNED_SUFFIX; + String unalignedApk = AndroidCommonUtils.addSuffixToFileName(finalApk, UNALIGNED_SUFFIX); Map> map2 = filterUsingKeystoreMessages( finalPackage(dexPath, sourceRoots, externalJars, nativeLibsFolders, withAlignment ? unalignedApk : finalApk, resPackagePath, diff --git a/plugins/android/common/src/org/jetbrains/android/util/AndroidCommonUtils.java b/plugins/android/common/src/org/jetbrains/android/util/AndroidCommonUtils.java index fa569419a208..432be8fbea6d 100644 --- a/plugins/android/common/src/org/jetbrains/android/util/AndroidCommonUtils.java +++ b/plugins/android/common/src/org/jetbrains/android/util/AndroidCommonUtils.java @@ -516,4 +516,15 @@ public class AndroidCommonUtils { } return result.toArray(new File[result.size()]); } + + @NotNull + public static String addSuffixToFileName(@NotNull String path, @NotNull String suffix) { + final int dot = path.lastIndexOf('.'); + if (dot < 0) { + return path + suffix; + } + final String a = path.substring(0, dot); + final String b = path.substring(dot); + return a + suffix + b; + } } diff --git a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidDexBuilder.java b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidDexBuilder.java index d0dc6b7ddd36..412989ddb4fa 100644 --- a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidDexBuilder.java +++ b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidDexBuilder.java @@ -110,11 +110,9 @@ public class AndroidDexBuilder extends ProjectLevelBuilder { } final ProjectPaths projectPaths = context.getProjectPaths(); - final File dexOutputDir = AndroidJpsUtil.getOutputDirectoryForPackagedFiles(projectPaths, module); - + File dexOutputDir = AndroidJpsUtil.getDirectoryForIntermediateArtifacts(context, module); + dexOutputDir = AndroidJpsUtil.createDirIfNotExist(dexOutputDir, context, BUILDER_NAME); if (dexOutputDir == null) { - context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, AndroidJpsBundle - .message("android.jps.errors.output.dir.not.specified", module.getName()))); success = false; continue; } @@ -125,7 +123,7 @@ public class AndroidDexBuilder extends ProjectLevelBuilder { .message("android.jps.warnings.dex.no.compiled.files", module.getName()))); continue; } - final Set externalLibraries = AndroidJpsUtil.getExternalLibraries(projectPaths, module, platform); + final Set externalLibraries = AndroidJpsUtil.getExternalLibraries(context, module, platform); boolean includeSystemProguardCfg = false; String proguardCfgPath = context.getBuilderParameter(AndroidCommonUtils.PROGUARD_CFG_PATH_OPTION); @@ -175,7 +173,7 @@ public class AndroidDexBuilder extends ProjectLevelBuilder { fileSet.addAll(externalLibraries); jars.addAll(externalLibraries); - AndroidJpsUtil.processClasspath(projectPaths, module, new AndroidDependencyProcessor() { + AndroidJpsUtil.processClasspath(context, module, new AndroidDependencyProcessor() { @Override public void processExternalLibrary(@NotNull File file) { fileSet.add(file.getPath()); @@ -372,7 +370,6 @@ public class AndroidDexBuilder extends ProjectLevelBuilder { return false; } - final ProjectPaths paths = context.getProjectPaths(); final Set classFilesDirs = new HashSet(); final Set libClassFilesDirs = new HashSet(); final Set outputDirs = new HashSet(); @@ -380,7 +377,7 @@ public class AndroidDexBuilder extends ProjectLevelBuilder { AndroidJpsUtil.addSubdirectories(classesDir, classFilesDirs); outputDirs.add(classesDir.getPath()); - AndroidJpsUtil.processClasspath(paths, module, new AndroidDependencyProcessor() { + AndroidJpsUtil.processClasspath(context, module, new AndroidDependencyProcessor() { @Override public void processAndroidLibraryOutputDirectory(@NotNull File dir) { diff --git a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidJpsUtil.java b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidJpsUtil.java index 9115b748026a..686dffead6db 100644 --- a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidJpsUtil.java +++ b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidJpsUtil.java @@ -37,7 +37,8 @@ class AndroidJpsUtil { private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.android.AndroidJpsUtil"); @NonNls public static final String ANDROID_STORAGE_DIR = "android"; - @NonNls private static final String RESOURCE_CACHE_STORAGE = "res-cache"; + @NonNls private static final String RESOURCE_CACHE_STORAGE = "res_cache"; + @NonNls private static final String INTERMEDIATE_ARTIFACTS_STORAGE = "intermediate_artifacts"; public static final Condition CLASSES_AND_JARS_FILTER = new Condition() { @Override @@ -142,10 +143,23 @@ class AndroidJpsUtil { return result; } + @NotNull + public static File getDirectoryForIntermediateArtifacts(@NotNull CompileContext context, + @NotNull Module module) { + final File androidStorage = new File(context.getDataManager().getDataStorageRoot(), ANDROID_STORAGE_DIR); + return new File(new File(androidStorage, INTERMEDIATE_ARTIFACTS_STORAGE), module.getName()); + } + @Nullable - public static File getOutputDirectoryForPackagedFiles(@NotNull ProjectPaths paths, @NotNull Module module) { - // todo: return build directory for mavenized modules to place .dex and .apk files into target dir (not target/classes) - return paths.getModuleOutputDir(module, false); + public static File createDirIfNotExist(@NotNull File dir, @NotNull CompileContext context, @NotNull String compilerName) { + if (!dir.exists()) { + if (!dir.mkdirs()) { + context.processMessage(new CompilerMessage(compilerName, BuildMessage.Kind.ERROR, + AndroidJpsBundle.message("android.jps.cannot.create.directory", dir.getPath()))); + return null; + } + } + return dir; } public static void addSubdirectories(@NotNull File baseDir, @NotNull Collection result) { @@ -162,7 +176,9 @@ class AndroidJpsUtil { } @NotNull - public static Set getExternalLibraries(@NotNull ProjectPaths paths, @NotNull Module module, @NotNull AndroidPlatform platform) { + public static Set getExternalLibraries(@NotNull CompileContext context, + @NotNull Module module, + @NotNull AndroidPlatform platform) { final Set result = new HashSet(); final AndroidDependencyProcessor processor = new AndroidDependencyProcessor() { @Override @@ -175,7 +191,7 @@ class AndroidJpsUtil { return type == AndroidDependencyType.EXTERNAL_LIBRARY; } }; - processClasspath(paths, module, processor); + processClasspath(context, module, processor); addAnnotationsJarIfNecessary(platform, result); return result; } @@ -191,18 +207,21 @@ class AndroidJpsUtil { } } - public static void processClasspath(@NotNull ProjectPaths paths, @NotNull Module module, @NotNull AndroidDependencyProcessor processor) { - processClasspath(paths, module, processor, new HashSet(), false); + public static void processClasspath(@NotNull CompileContext context, + @NotNull Module module, + @NotNull AndroidDependencyProcessor processor) { + processClasspath(context, module, processor, new HashSet(), false); } - private static void processClasspath(@NotNull ProjectPaths paths, - @NotNull final Module module, - @NotNull final AndroidDependencyProcessor processor, - @NotNull final Set visitedModules, - final boolean exportedLibrariesOnly) { + private static void processClasspath(@NotNull CompileContext context, + @NotNull final Module module, + @NotNull final AndroidDependencyProcessor processor, + @NotNull final Set visitedModules, + final boolean exportedLibrariesOnly) { if (!visitedModules.add(module.getName())) { return; } + final ProjectPaths paths = context.getProjectPaths(); if (processor.isToProcess(AndroidDependencyType.EXTERNAL_LIBRARY)) { for (ClasspathItem item : module.getClasspath(ClasspathKind.PRODUCTION_RUNTIME, exportedLibrariesOnly)) { @@ -232,25 +251,29 @@ class AndroidJpsUtil { final boolean depLibrary = depFacet != null && depFacet.isLibrary(); final File depClassDir = paths.getModuleOutputDir(depModule, false); - if (depClassDir != null) { - if (depLibrary) { - if (processor.isToProcess(AndroidDependencyType.ANDROID_LIBRARY_PACKAGE)) { - final File packagedClassesJar = new File(depClassDir, AndroidCommonUtils.CLASSES_JAR_FILE_NAME); + if (depLibrary) { + if (processor.isToProcess(AndroidDependencyType.ANDROID_LIBRARY_PACKAGE)) { + final File intArtifactsDir = getDirectoryForIntermediateArtifacts(context, depModule); + final File packagedClassesJar = new File(intArtifactsDir, AndroidCommonUtils.CLASSES_JAR_FILE_NAME); - if (packagedClassesJar.isFile()) { - processor.processAndroidLibraryPackage(packagedClassesJar); - } + if (packagedClassesJar.isFile()) { + processor.processAndroidLibraryPackage(packagedClassesJar); } - if (processor.isToProcess(AndroidDependencyType.ANDROID_LIBRARY_OUTPUT_DIRECTORY)) { + } + if (processor.isToProcess(AndroidDependencyType.ANDROID_LIBRARY_OUTPUT_DIRECTORY)) { + if (depClassDir != null && depClassDir.isDirectory()) { processor.processAndroidLibraryOutputDirectory(depClassDir); } } - else if (processor.isToProcess(AndroidDependencyType.JAVA_MODULE_OUTPUT_DIR) && depFacet == null && depClassDir.isDirectory()) { - // do not support android-app->android-app compile dependencies - processor.processJavaModuleOutputDirectory(depClassDir); - } } - processClasspath(paths, depModule, processor, visitedModules, !depLibrary || exportedLibrariesOnly); + else if (processor.isToProcess(AndroidDependencyType.JAVA_MODULE_OUTPUT_DIR) && + depFacet == null && + depClassDir != null && + depClassDir.isDirectory()) { + // do not support android-app->android-app compile dependencies + processor.processJavaModuleOutputDirectory(depClassDir); + } + processClasspath(context, depModule, processor, visitedModules, !depLibrary || exportedLibrariesOnly); } } } diff --git a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidLibraryPackagingBuilder.java b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidLibraryPackagingBuilder.java index ce3943375a6f..ef0c0a770bb3 100644 --- a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidLibraryPackagingBuilder.java +++ b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidLibraryPackagingBuilder.java @@ -11,8 +11,6 @@ import org.jetbrains.jps.incremental.BuilderCategory; import org.jetbrains.jps.incremental.CompileContext; import org.jetbrains.jps.incremental.ModuleLevelBuilder; import org.jetbrains.jps.incremental.ProjectBuildException; -import org.jetbrains.jps.incremental.messages.BuildMessage; -import org.jetbrains.jps.incremental.messages.CompilerMessage; import org.jetbrains.jps.incremental.messages.ProgressMessage; import java.io.File; @@ -54,11 +52,9 @@ public class AndroidLibraryPackagingBuilder extends ModuleLevelBuilder { } final ProjectPaths projectPaths = context.getProjectPaths(); - final File outputDirectoryForPackagedFiles = AndroidJpsUtil.getOutputDirectoryForPackagedFiles(projectPaths, module); - - if (outputDirectoryForPackagedFiles == null) { - context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, AndroidJpsBundle - .message("android.jps.errors.output.dir.not.specified", module.getName()))); + File outputDir = AndroidJpsUtil.getDirectoryForIntermediateArtifacts(context, module); + outputDir = AndroidJpsUtil.createDirIfNotExist(outputDir, context, BUILDER_NAME); + if (outputDir == null) { success = false; continue; } @@ -80,7 +76,7 @@ public class AndroidLibraryPackagingBuilder extends ModuleLevelBuilder { if (subdirs.size() > 0) { context.processMessage(new ProgressMessage(AndroidJpsBundle.message("android.jps.progress.library.packaging", module.getName()))); - final File outputJarFile = new File(outputDirectoryForPackagedFiles, AndroidCommonUtils.CLASSES_JAR_FILE_NAME); + final File outputJarFile = new File(outputDir, AndroidCommonUtils.CLASSES_JAR_FILE_NAME); doneSomething = true; try { AndroidCommonUtils.packClassFilesIntoJar(ArrayUtil.EMPTY_STRING_ARRAY, ArrayUtil.toStringArray(subdirs), outputJarFile); diff --git a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java index 2192dc9b932a..6779cccdac72 100644 --- a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java +++ b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java @@ -333,8 +333,10 @@ public class AndroidPackagingBuilder extends ProjectLevelBuilder { final String[] sourceRoots = AndroidJpsUtil.toPaths(AndroidJpsUtil.getSourceRootsForModuleAndDependencies(module)); final ProjectPaths paths = context.getProjectPaths(); - final File outputDir = AndroidJpsUtil.getOutputDirectoryForPackagedFiles(paths, module); - if (outputDir == null) { + final File intArtifactsDir = AndroidJpsUtil.getDirectoryForIntermediateArtifacts(context, module); + + final File moduleOutputDir = paths.getModuleOutputDir(module, false); + if (moduleOutputDir == null) { context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, AndroidJpsBundle .message("android.jps.errors.output.dir.not.specified", module.getName()))); return false; @@ -345,13 +347,13 @@ public class AndroidPackagingBuilder extends ProjectLevelBuilder { return false; } - final Set externalJarsSet = AndroidJpsUtil.getExternalLibraries(paths, module, platform); - final File resPackage = getPackagedResourcesFile(module, outputDir); + final Set externalJarsSet = AndroidJpsUtil.getExternalLibraries(context, module, platform); + final File resPackage = getPackagedResourcesFile(module, intArtifactsDir); - final File classesDexFile = new File(outputDir.getPath(), AndroidCommonUtils.CLASSES_FILE_NAME); + final File classesDexFile = new File(intArtifactsDir.getPath(), AndroidCommonUtils.CLASSES_FILE_NAME); final String sdkPath = platform.getSdk().getSdkPath(); - final String outputPath = AndroidJpsUtil.getApkPath(facet, outputDir); + final String outputPath = AndroidJpsUtil.getApkPath(facet, moduleOutputDir); if (outputPath == null) { context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, AndroidJpsBundle .message("android.jps.errors.cannot.compute.output.apk", module.getName()))); @@ -361,7 +363,11 @@ public class AndroidPackagingBuilder extends ProjectLevelBuilder { final String[] nativeLibDirs = collectNativeLibsFolders(facet); final String resPackagePath = release ? resPackage.getPath() + RELEASE_SUFFIX : resPackage.getPath(); - final String outputApkPath = release ? outputPath + UNSIGNED_SUFFIX : outputPath; + + final String outputApkPath = release + ? AndroidCommonUtils.addSuffixToFileName(outputPath, UNSIGNED_SUFFIX) + : outputPath; + final String classesDexFilePath = classesDexFile.getPath(); final String[] externalJars = ArrayUtil.toStringArray(externalJarsSet); @@ -474,10 +480,9 @@ public class AndroidPackagingBuilder extends ProjectLevelBuilder { final ArrayList assetsDirPaths = new ArrayList(); collectAssetDirs(facet, assetsDirPaths); - final File outputDir = AndroidJpsUtil.getOutputDirectoryForPackagedFiles(context.getProjectPaths(), module); + File outputDir = AndroidJpsUtil.getDirectoryForIntermediateArtifacts(context, module); + outputDir = AndroidJpsUtil.createDirIfNotExist(outputDir, context, BUILDER_NAME); if (outputDir == null) { - context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, AndroidJpsBundle - .message("android.jps.errors.output.dir.not.specified", module.getName()))); return false; } diff --git a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidSourceGeneratingBuilder.java b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidSourceGeneratingBuilder.java index 265845566c92..8f38c85b047b 100644 --- a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidSourceGeneratingBuilder.java +++ b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidSourceGeneratingBuilder.java @@ -91,6 +91,12 @@ public class AndroidSourceGeneratingBuilder extends ModuleLevelBuilder { } checkAndroidDependencies(moduleDataMap, context); + if (context.isProjectRebuild()) { + if (!clearAndroidStorages(context, chunk.getModules())) { + return ExitCode.ABORT; + } + } + final Map idlFilesToCompile = new HashMap(); final Map rsFilesToCompile = new HashMap(); @@ -169,6 +175,18 @@ public class AndroidSourceGeneratingBuilder extends ModuleLevelBuilder { return success ? ExitCode.OK : ExitCode.ABORT; } + private static boolean clearAndroidStorages(@NotNull CompileContext context, @NotNull Collection modules) { + for (Module module : modules) { + final File dir = AndroidJpsUtil.getDirectoryForIntermediateArtifacts(context, module); + if (dir.exists() && !FileUtil.delete(dir)) { + context.processMessage( + new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, AndroidJpsBundle.message("android.jps.cannot.delete", dir.getPath()))); + return false; + } + } + return true; + } + private static boolean checkVersions(@NotNull Map dataMap, @NotNull CompileContext context) { for (Map.Entry entry : dataMap.entrySet()) { final Module module = entry.getKey(); @@ -581,12 +599,16 @@ public class AndroidSourceGeneratingBuilder extends ModuleLevelBuilder { success = false; continue; } - if (!FileUtil.moveDirWithContent(tmpOutputDir, aptOutputDirectory)) { - context.processMessage(new CompilerMessage(ANDROID_APT_COMPILER, BuildMessage.Kind.ERROR, AndroidJpsBundle - .message("android.jps.errors.cannot.move.content", tmpOutputDir.getPath(), aptOutputDirectory.getPath()))); + final File parent = aptOutputDirectory.getParentFile(); + if (parent != null && !parent.exists() && !parent.mkdirs()) { + context.processMessage(new CompilerMessage(ANDROID_APT_COMPILER, BuildMessage.Kind.ERROR, AndroidJpsBundle.message( + "android.jps.cannot.create.directory", parent.getPath()))); success = false; continue; } + // we use copyDir instead of moveDirWithContent here, because tmp directory may be located on other disk and + // moveDirWithContent doesn't work for such case + FileUtil.copyDir(tmpOutputDir, aptOutputDirectory); markDirtyRecursively(aptOutputDirectory, context, ANDROID_APT_COMPILER); } storage.update(module.getName(), newState); diff --git a/plugins/android/src/org/jetbrains/android/compiler/AndroidAptCompiler.java b/plugins/android/src/org/jetbrains/android/compiler/AndroidAptCompiler.java index e06710b619e5..5ce2bfdc5652 100644 --- a/plugins/android/src/org/jetbrains/android/compiler/AndroidAptCompiler.java +++ b/plugins/android/src/org/jetbrains/android/compiler/AndroidAptCompiler.java @@ -117,11 +117,14 @@ public class AndroidAptCompiler implements SourceGeneratingCompiler { context.addMessage(CompilerMessageCategory.ERROR, "Cannot delete directory " + genRootPath, null, -1, -1); continue; } - if (!FileUtil.moveDirWithContent(tmpOutputDir, genRootDir)) { - final String message = "Cannot move content from " + tmpOutputDir.getPath() + " to " + genRootPath; - context.addMessage(CompilerMessageCategory.ERROR, message, null, -1, -1); + final File parent = genRootDir.getParentFile(); + if (parent != null && !parent.exists() && !parent.mkdirs()) { + context.addMessage(CompilerMessageCategory.ERROR, "Cannot create directory " + parent.getPath(), null, -1, -1); continue; } + // we use copyDir instead of moveDirWithContent here, because tmp directory may be located on other disk and + // moveDirWithContent doesn't work for such case + FileUtil.copyDir(tmpOutputDir, genRootDir); } results.add(aptItem); } diff --git a/plugins/android/src/org/jetbrains/android/compiler/AndroidPackagingCompiler.java b/plugins/android/src/org/jetbrains/android/compiler/AndroidPackagingCompiler.java index a5e34b7a4ab9..3cf23e95fcd2 100644 --- a/plugins/android/src/org/jetbrains/android/compiler/AndroidPackagingCompiler.java +++ b/plugins/android/src/org/jetbrains/android/compiler/AndroidPackagingCompiler.java @@ -235,7 +235,7 @@ public class AndroidPackagingCompiler implements PackagingCompiler { : item.getResPackagePath(); final String finalPath = unsigned - ? item.getFinalPath() + UNSIGNED_SUFFIX + ? AndroidCommonUtils.addSuffixToFileName(item.getFinalPath(), UNSIGNED_SUFFIX) : item.getFinalPath(); final String[] sourceRoots = AndroidCompileUtil.toOsPaths(item.getSourceRoots()); diff --git a/plugins/android/src/org/jetbrains/android/inspections/lint/ProblemData.java b/plugins/android/src/org/jetbrains/android/inspections/lint/ProblemData.java index 72805b19ae45..a4ab9a846116 100644 --- a/plugins/android/src/org/jetbrains/android/inspections/lint/ProblemData.java +++ b/plugins/android/src/org/jetbrains/android/inspections/lint/ProblemData.java @@ -7,7 +7,7 @@ import org.jetbrains.annotations.NotNull; /** * @author Eugene.Kudelevsky */ -class ProblemData { +public class ProblemData { private final Issue myIssue; private final String myMessage; private final TextRange myTextRange; diff --git a/plugins/android/src/org/jetbrains/android/inspections/lint/State.java b/plugins/android/src/org/jetbrains/android/inspections/lint/State.java index 9793e507d201..9b27e0e163a0 100644 --- a/plugins/android/src/org/jetbrains/android/inspections/lint/State.java +++ b/plugins/android/src/org/jetbrains/android/inspections/lint/State.java @@ -11,7 +11,7 @@ import java.util.List; /** * @author Eugene.Kudelevsky */ -class State { +public class State { private final Module myModule; private final VirtualFile myMainFile; diff --git a/plugins/git4idea/src/git4idea/GitUtil.java b/plugins/git4idea/src/git4idea/GitUtil.java index 4c4879a483ab..2dcc24f0c017 100644 --- a/plugins/git4idea/src/git4idea/GitUtil.java +++ b/plugins/git4idea/src/git4idea/GitUtil.java @@ -508,7 +508,7 @@ public class GitUtil { if ((!firstStep) && lineIsAStart) { final StringScanner innerScanner = new StringScanner(sb.toString()); sb.setLength(0); - consumer.consume(GitChangeUtils.parseChangeList(project, root, innerScanner, skipDiffsForMerge, h)); + consumer.consume(GitChangeUtils.parseChangeList(project, root, innerScanner, skipDiffsForMerge, h, false)); } sb.append(lineIsAStart ? line.substring(2) : line).append('\n'); firstStep = false; @@ -516,7 +516,7 @@ public class GitUtil { if (sb.length() > 0) { final StringScanner innerScanner = new StringScanner(sb.toString()); sb.setLength(0); - consumer.consume(GitChangeUtils.parseChangeList(project, root, innerScanner, skipDiffsForMerge, h)); + consumer.consume(GitChangeUtils.parseChangeList(project, root, innerScanner, skipDiffsForMerge, h, false)); } if (s.hasMoreData()) { throw new IllegalStateException("More input is avaialble: " + s.line()); diff --git a/plugins/git4idea/src/git4idea/actions/GitShowAllSubmittedFilesAction.java b/plugins/git4idea/src/git4idea/actions/GitShowAllSubmittedFilesAction.java index a97f569e70b8..b0f760edd2c8 100644 --- a/plugins/git4idea/src/git4idea/actions/GitShowAllSubmittedFilesAction.java +++ b/plugins/git4idea/src/git4idea/actions/GitShowAllSubmittedFilesAction.java @@ -86,7 +86,7 @@ public class GitShowAllSubmittedFilesAction extends AnAction implements DumbAwar * @param file file affected by the revision */ public static void showSubmittedFiles(final Project project, final VcsFileRevision revision, final VirtualFile file) { - showSubmittedFiles(project, revision.getRevisionNumber().asString(), file); + showSubmittedFiles(project, revision.getRevisionNumber().asString(), file, false); } /** @@ -95,14 +95,15 @@ public class GitShowAllSubmittedFilesAction extends AnAction implements DumbAwar * @param project a project * @param revision a revision number * @param file file affected by the revision + * @param local */ - public static void showSubmittedFiles(final Project project, final String revision, final VirtualFile file) { + public static void showSubmittedFiles(final Project project, final String revision, final VirtualFile file, final boolean local) { new Task.Backgroundable(project, GitBundle.message("changes.retrieving", revision)) { public void run(@NotNull ProgressIndicator indicator) { indicator.setIndeterminate(true); try { VirtualFile vcsRoot = GitUtil.getGitRoot(file); - final CommittedChangeList changeList = GitChangeUtils.getRevisionChanges(project, vcsRoot, revision, true); + final CommittedChangeList changeList = GitChangeUtils.getRevisionChanges(project, vcsRoot, revision, true, local); if (changeList != null) { UIUtil.invokeLaterIfNeeded(new Runnable() { public void run() { diff --git a/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java b/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java index 4e5f4af077cc..c0080c347893 100644 --- a/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java +++ b/plugins/git4idea/src/git4idea/changes/GitChangeUtils.java @@ -122,7 +122,7 @@ public class GitChangeUtils { public static void parseChanges(Project project, VirtualFile vcsRoot, @Nullable GitRevisionNumber thisRevision, - GitRevisionNumber parentRevision, + @Nullable GitRevisionNumber parentRevision, StringScanner s, Collection changes, final Set ignoreNames) throws VcsException { @@ -230,14 +230,20 @@ public class GitChangeUtils { * of the merge, so changes are reported as difference with the first revision * listed on the the merge that has at least some changes. * + * * @param project the project file * @param root the git root * @param revisionName the name of revision (might be tag) * @param skipDiffsForMerge + * @param local * @return change list for the respective revision * @throws VcsException in case of problem with running git */ - public static GitCommittedChangeList getRevisionChanges(Project project, VirtualFile root, String revisionName, boolean skipDiffsForMerge) throws VcsException { + public static GitCommittedChangeList getRevisionChanges(Project project, + VirtualFile root, + String revisionName, + boolean skipDiffsForMerge, + boolean local) throws VcsException { GitSimpleHandler h = new GitSimpleHandler(project, root, GitCommand.SHOW); h.setNoSSH(true); h.setSilent(true); @@ -245,7 +251,7 @@ public class GitChangeUtils { revisionName, "--"); String output = h.run(); StringScanner s = new StringScanner(output); - return parseChangeList(project, root, s, skipDiffsForMerge, h); + return parseChangeList(project, root, s, skipDiffsForMerge, h, local); } @Nullable @@ -328,15 +334,24 @@ public class GitChangeUtils { /** * Parse changelist * + * * @param project the project * @param root the git root * @param s the scanner for log or show command output * @param skipDiffsForMerge * @param handler the handler that produced the output to parse. - for debugging purposes. + * @param local pass {@code true} to indicate that this revision should be an editable + * {@link com.intellij.openapi.vcs.changes.CurrentContentRevision}. + * Pass {@code false} for * @return the parsed changelist * @throws VcsException if there is a problem with running git */ - public static GitCommittedChangeList parseChangeList(Project project, VirtualFile root, StringScanner s, boolean skipDiffsForMerge, GitHandler handler) throws VcsException { + public static GitCommittedChangeList parseChangeList(Project project, + VirtualFile root, + StringScanner s, + boolean skipDiffsForMerge, + GitHandler handler, + boolean local) throws VcsException { ArrayList changes = new ArrayList(); // parse commit information final Date commitDate = GitUtil.parseTimestampWithNFEReport(s.line(), handler, s.getAllText()); @@ -367,7 +382,7 @@ public class GitChangeUtils { final GitRevisionNumber parentRevision = parents.length > 0 ? loadRevision(project, root, parents[0]) : null; // This is the first or normal commit with the single parent. // Just parse changes in this commit as returned by the show command. - parseChanges(project, root, thisRevision, parentRevision, s, changes, null); + parseChanges(project, root, thisRevision, local ? null : parentRevision, s, changes, null); } else { // This is the merge commit. It has multiple parent commits. @@ -376,10 +391,6 @@ public class GitChangeUtils { for (String parent : parents) { final GitRevisionNumber parentRevision = loadRevision(project, root, parent); - if (parentRevision == null) { - // the repository was cloned with --depth parameter - continue; - } GitSimpleHandler diffHandler = new GitSimpleHandler(project, root, GitCommand.DIFF); diffHandler.setNoSSH(true); diffHandler.setSilent(true); diff --git a/plugins/git4idea/src/git4idea/checkin/GitCheckinEnvironment.java b/plugins/git4idea/src/git4idea/checkin/GitCheckinEnvironment.java index 0f4237443533..88873bd2a6a1 100644 --- a/plugins/git4idea/src/git4idea/checkin/GitCheckinEnvironment.java +++ b/plugins/git4idea/src/git4idea/checkin/GitCheckinEnvironment.java @@ -142,6 +142,7 @@ public class GitCheckinEnvironment implements CheckinEnvironment { @NotNull NullableFunction parametersHolder, Set feedback) { List exceptions = new ArrayList(); Map> sortedChanges = sortChangesByGitRoot(changes, exceptions); + log.assertTrue(!sortedChanges.isEmpty(), "Trying to commit an empty list of changes: " + changes); if (GitFileSeparatorConverter.convertSeparatorsIfNeeded(myProject, mySettings, sortedChanges, exceptions)) { for (Map.Entry> entry : sortedChanges.entrySet()) { Set files = new HashSet(); diff --git a/plugins/git4idea/src/git4idea/commands/GitCommand.java b/plugins/git4idea/src/git4idea/commands/GitCommand.java index 2528424c8d1a..11938ad7d5e2 100644 --- a/plugins/git4idea/src/git4idea/commands/GitCommand.java +++ b/plugins/git4idea/src/git4idea/commands/GitCommand.java @@ -136,4 +136,8 @@ public class GitCommand { return new GitCommand(this, LockingPolicy.READ); } + @Override + public String toString() { + return myName; + } } diff --git a/plugins/git4idea/src/git4idea/commands/GitHandler.java b/plugins/git4idea/src/git4idea/commands/GitHandler.java index c6c33d227d2d..4dba365526a5 100644 --- a/plugins/git4idea/src/git4idea/commands/GitHandler.java +++ b/plugins/git4idea/src/git4idea/commands/GitHandler.java @@ -96,6 +96,9 @@ public abstract class GitHandler { private Runnable mySuspendAction; // Suspend action used by {@link #suspendWriteLock()} private Runnable myResumeAction; // Resume action used by {@link #resumeWriteLock()} + private long myStartTime; // git execution start timestamp + private static final long LONG_TIME = 10 * 1000; + /** * A constructor @@ -387,12 +390,19 @@ public abstract class GitHandler { checkNotStarted(); try { - // setup environment + myStartTime = System.currentTimeMillis(); if (!myProject.isDefault() && !mySilent && (myVcs != null)) { myVcs.showCommandLine("cd " + myWorkingDirectory); myVcs.showCommandLine(printableCommandLine()); + LOG.info("cd " + myWorkingDirectory); LOG.info(myCommandLine.getCommandLineString()); } + else { + LOG.debug("cd " + myWorkingDirectory); + LOG.debug(myCommandLine.getCommandLineString()); + } + + // setup environment if (!myNoSSHFlag && myProjectSettings.isIdeaSsh()) { GitSSHService ssh = GitSSHIdeaService.getInstance(); myEnv.put(GitSSHHandler.GIT_SSH_ENV, ssh.getScriptPath().getPath()); @@ -721,6 +731,23 @@ public abstract class GitHandler { vcs.getCommandLock().writeLock().unlock(); break; } + + logTime(); + } + } + + private void logTime() { + if (myStartTime > 0) { + long time = System.currentTimeMillis() - myStartTime; + if (!LOG.isDebugEnabled() && time > LONG_TIME) { + LOG.info(String.format("git %s took %s ms. Command parameters: %n%s", myCommand, time, myCommandLine.getCommandLineString())); + } + else { + LOG.debug(String.format("git %s took %s ms", myCommand, time)); + } + } + else { + LOG.debug(String.format("git %s finished.", myCommand)); } } diff --git a/plugins/git4idea/src/git4idea/history/browser/CherryPicker.java b/plugins/git4idea/src/git4idea/history/browser/GitCherryPicker.java similarity index 95% rename from plugins/git4idea/src/git4idea/history/browser/CherryPicker.java rename to plugins/git4idea/src/git4idea/history/browser/GitCherryPicker.java index 52c77d4516cb..c391836019fb 100644 --- a/plugins/git4idea/src/git4idea/history/browser/CherryPicker.java +++ b/plugins/git4idea/src/git4idea/history/browser/GitCherryPicker.java @@ -58,7 +58,7 @@ import static git4idea.commands.GitMessageWithFilesDetector.Event.UNTRACKED_FILE import static git4idea.commands.GitSimpleEventDetector.Event.CHERRY_PICK_CONFLICT; import static git4idea.commands.GitSimpleEventDetector.Event.LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK; -public class CherryPicker { +public class GitCherryPicker { /** * Name of the {@code .git/CHERRY_PICK_HEAD} file which is stored under {@code .git} when cherry-pick is in progress, @@ -66,7 +66,7 @@ public class CherryPicker { */ private static final String CHERRY_PICK_HEAD_FILE = "CHERRY_PICK_HEAD"; - private static final Logger LOG = Logger.getInstance(CherryPicker.class); + private static final Logger LOG = Logger.getInstance(GitCherryPicker.class); @NotNull private final Project myProject; @NotNull private final Git myGit; @@ -74,7 +74,7 @@ public class CherryPicker { @NotNull private final ChangeListManager myChangeListManager; private final boolean myAutoCommit; - public CherryPicker(@NotNull Project project, @NotNull Git git, @NotNull PlatformFacade platformFacade, boolean autoCommit) { + public GitCherryPicker(@NotNull Project project, @NotNull Git git, @NotNull PlatformFacade platformFacade, boolean autoCommit) { myProject = project; myGit = git; myPlatformFacade = platformFacade; @@ -187,6 +187,10 @@ public class CherryPicker { } private void notifyCommitCancelled(@NotNull GitCommit commit, @NotNull List successfulCommits) { + if (successfulCommits.isEmpty()) { + // don't notify about cancelled commit. Notify just in the case when there were already successful commits in the queue. + return; + } String description = commitDetails(commit); description += getSuccessfulCommitDetailsIfAny(successfulCommits); myPlatformFacade.getNotificator(myProject).notifyWeakWarning("Cherry-pick cancelled", description, null); @@ -493,21 +497,20 @@ public class CherryPicker { final Collection committingDocs = markCommittingDocs(); try { CheckinEnvironment ce = myPlatformFacade.getVcs(myProject).getCheckinEnvironment(); - if (ce != null && ce instanceof GitCheckinEnvironment) { - try { - ((GitCheckinEnvironment)ce).reset(); - List exceptions = ce.commit(myChanges, myCommitMessage); - VcsDirtyScopeManager.getInstance(myProject).filePathsDirty(ChangesUtil.getPaths(myChanges), null); - if (exceptions != null && !exceptions.isEmpty()) { - VcsException exception = exceptions.get(0); - handleError(exception); - } - } - catch (Throwable e) { - LOG.error(e); - handleError(e); + LOG.assertTrue(ce != null && ce instanceof GitCheckinEnvironment, "Invalid CheckinEnvironment: " + ce); + try { + ((GitCheckinEnvironment)ce).reset(); + List exceptions = ce.commit(myChanges, myCommitMessage); + VcsDirtyScopeManager.getInstance(myProject).filePathsDirty(ChangesUtil.getPaths(myChanges), null); + if (exceptions != null && !exceptions.isEmpty()) { + VcsException exception = exceptions.get(0); + handleError(exception); } } + catch (Throwable e) { + LOG.error(e); + handleError(e); + } } finally { unmarkCommittingDocs(committingDocs); diff --git a/plugins/git4idea/src/git4idea/history/wholeTree/GitLogUI.java b/plugins/git4idea/src/git4idea/history/wholeTree/GitLogUI.java index 53e7e5b99d19..93e2f165cc58 100644 --- a/plugins/git4idea/src/git4idea/history/wholeTree/GitLogUI.java +++ b/plugins/git4idea/src/git4idea/history/wholeTree/GitLogUI.java @@ -1618,7 +1618,7 @@ public class GitLogUI implements Disposable { public void run(@NotNull ProgressIndicator indicator) { boolean autoCommit = GitVcsSettings.getInstance(myProject).isAutoCommitOnCherryPick(); Map> commitsInRoots = prepareCommitsForCherryPick(commits); - new CherryPicker(myProject, ServiceManager.getService(Git.class), ServiceManager.getService(PlatformFacade.class), autoCommit) + new GitCherryPicker(myProject, ServiceManager.getService(Git.class), ServiceManager.getService(PlatformFacade.class), autoCommit) .cherryPick(commitsInRoots); ApplicationManager.getApplication().invokeLater(new Runnable() { @@ -1864,11 +1864,16 @@ public class GitLogUI implements Disposable { } public class MyShowTreeAction extends ToggleAction implements DumbAware { + private static final String SHOW_GRAPH_TITLE = "Show Graph"; + private static final String HIDE_GRAPH_TITLE = "Hide Graph"; + private static final String SHOW_GRAPH_DESCRIPTION = "Display commit graph"; + private static final String HIDE_GRAPH_DESCRIPTION = "Hide commit graph"; + private boolean myIsSelected; private final GitLogSettings myInstance; public MyShowTreeAction() { - super("Show Graph", "Display commit graph", IconLoader.getIcon("/icons/branch.png")); + super(SHOW_GRAPH_TITLE, SHOW_GRAPH_DESCRIPTION, IconLoader.getIcon("/icons/branch.png")); myInstance = GitLogSettings.getInstance(myProject); myIsSelected = myInstance.isShowTree(); } @@ -1877,6 +1882,8 @@ public class GitLogUI implements Disposable { public void update(AnActionEvent e) { super.update(e); e.getPresentation().setEnabled(!myThereAreFilters); + e.getPresentation().setText(isSelected(e) ? HIDE_GRAPH_TITLE : SHOW_GRAPH_TITLE); + e.getPresentation().setDescription(isSelected(e) ? HIDE_GRAPH_DESCRIPTION : SHOW_GRAPH_DESCRIPTION); } @Override diff --git a/plugins/git4idea/src/git4idea/rebase/GitRebaseEditor.java b/plugins/git4idea/src/git4idea/rebase/GitRebaseEditor.java index e1332d5ba92b..a0225ad98d98 100644 --- a/plugins/git4idea/src/git4idea/rebase/GitRebaseEditor.java +++ b/plugins/git4idea/src/git4idea/rebase/GitRebaseEditor.java @@ -133,7 +133,7 @@ public class GitRebaseEditor extends DialogWrapper { return; } GitRebaseEntry entry = myTableModel.myEntries.get(row); - GitShowAllSubmittedFilesAction.showSubmittedFiles(project, entry.getCommit(), gitRoot); + GitShowAllSubmittedFilesAction.showSubmittedFiles(project, entry.getCommit(), gitRoot, false); } }); diff --git a/plugins/git4idea/src/git4idea/repo/GitUntrackedFilesHolder.java b/plugins/git4idea/src/git4idea/repo/GitUntrackedFilesHolder.java index 44c4e7355667..389c20aafa2b 100644 --- a/plugins/git4idea/src/git4idea/repo/GitUntrackedFilesHolder.java +++ b/plugins/git4idea/src/git4idea/repo/GitUntrackedFilesHolder.java @@ -17,6 +17,7 @@ package git4idea.repo; import com.intellij.openapi.Disposable; import com.intellij.openapi.components.ServiceManager; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.ChangeListManager; @@ -82,6 +83,8 @@ import java.util.*; */ public class GitUntrackedFilesHolder implements Disposable, BulkFileListener { + private static final Logger LOG = Logger.getInstance(GitUntrackedFilesHolder.class); + private final Project myProject; private final VirtualFile myRoot; private final ChangeListManager myChangeListManager; @@ -103,7 +106,6 @@ public class GitUntrackedFilesHolder implements Disposable, BulkFileListener { myGit = ServiceManager.getService(Git.class); myRepositoryManager = GitUtil.getRepositoryManager(myProject); - assert myRepositoryManager != null; myRepositoryFiles = GitRepositoryFiles.getInstance(repository.getGitDir()); } @@ -204,6 +206,7 @@ public class GitUntrackedFilesHolder implements Disposable, BulkFileListener { Set untrackedFiles = myGit.untrackedFiles(myProject, myRoot, suspiciousFiles); suspiciousFiles.removeAll(untrackedFiles); // files that were suspicious (and thus passed to 'git ls-files'), but are not untracked, are definitely tracked. + @SuppressWarnings("UnnecessaryLocalVariable") Set trackedFiles = suspiciousFiles; myDefinitelyUntrackedFiles.addAll(untrackedFiles); @@ -242,6 +245,7 @@ public class GitUntrackedFilesHolder implements Disposable, BulkFileListener { // if index has changed, no need to refresh specific files - we get the full status of all files if (allChanged) { + LOG.info(String.format("GitUntrackedFilesHolder: Index has changed, marking %s recursively dirty", myRoot)); myDirtyScopeManager.dirDirtyRecursively(myRoot); synchronized (LOCK) { myReady = false; diff --git a/plugins/git4idea/src/git4idea/status/GitChangeProvider.java b/plugins/git4idea/src/git4idea/status/GitChangeProvider.java index 94b3e69e7e47..58d834217064 100644 --- a/plugins/git4idea/src/git4idea/status/GitChangeProvider.java +++ b/plugins/git4idea/src/git4idea/status/GitChangeProvider.java @@ -41,12 +41,14 @@ import java.util.Set; * Git repository change provider */ public class GitChangeProvider implements ChangeProvider { - private static final Logger LOG = Logger.getInstance(GitChangeProvider.class); - private final Project myProject; + + private static final Logger PROFILE_LOG = Logger.getInstance("#GitStatus"); + + @NotNull private final Project myProject; @NotNull private final Git myGit; - private final ChangeListManager myChangeListManager; - private FileDocumentManager myFileDocumentManager; - private final ProjectLevelVcsManager myVcsManager; + @NotNull private final ChangeListManager myChangeListManager; + @NotNull private final FileDocumentManager myFileDocumentManager; + @NotNull private final ProjectLevelVcsManager myVcsManager; public GitChangeProvider(@NotNull Project project, @NotNull Git git, ChangeListManager changeListManager, @NotNull FileDocumentManager fileDocumentManager, @NotNull ProjectLevelVcsManager vcsManager) { @@ -113,6 +115,14 @@ public class GitChangeProvider implements ChangeProvider { return GitVersionSpecialty.KNOWS_STATUS_PORCELAIN.existsIn(version); } + /** + * Common debug logging method for all Git status related operations. + * Primarily used for measuring performance and tracking calls to heavy methods. + */ + public static void debug(String message) { + PROFILE_LOG.debug(message); + } + private static class MyNonChangedHolder { private final Project myProject; private final Set myDirty; diff --git a/plugins/git4idea/src/git4idea/ui/GitReferenceValidator.java b/plugins/git4idea/src/git4idea/ui/GitReferenceValidator.java index eb652deb8702..125992f17c6e 100644 --- a/plugins/git4idea/src/git4idea/ui/GitReferenceValidator.java +++ b/plugins/git4idea/src/git4idea/ui/GitReferenceValidator.java @@ -94,7 +94,7 @@ public class GitReferenceValidator { myLastResult = false; try { GitRevisionNumber revision = GitRevisionNumber.resolve(myProject, gitRoot(), revisionExpression); - GitShowAllSubmittedFilesAction.showSubmittedFiles(myProject, revision.asString(), gitRoot()); + GitShowAllSubmittedFilesAction.showSubmittedFiles(myProject, revision.asString(), gitRoot(), false); myLastResult = true; } catch (VcsException ex) { diff --git a/plugins/git4idea/src/git4idea/ui/GitUnstashDialog.java b/plugins/git4idea/src/git4idea/ui/GitUnstashDialog.java index 61ce16bfe79a..bf3d7793306b 100644 --- a/plugins/git4idea/src/git4idea/ui/GitUnstashDialog.java +++ b/plugins/git4idea/src/git4idea/ui/GitUnstashDialog.java @@ -124,6 +124,7 @@ public class GitUnstashDialog extends DialogWrapper { */ public GitUnstashDialog(final Project project, final List roots, final VirtualFile defaultRoot) { super(project, true); + setModal(false); myProject = project; myVcs = GitVcs.getInstance(project); setTitle(GitBundle.getString("unstash.title")); @@ -223,7 +224,7 @@ public class GitUnstashDialog extends DialogWrapper { GitUIUtil.showOperationError(myProject, ex, "resolving revision"); return; } - GitShowAllSubmittedFilesAction.showSubmittedFiles(myProject, resolvedStash, root); + GitShowAllSubmittedFilesAction.showSubmittedFiles(myProject, resolvedStash, root, true); } }); init(); diff --git a/plugins/git4idea/tests/git4idea/cherrypick/GitAutoCommittingCherryPickTest.groovy b/plugins/git4idea/tests/git4idea/cherrypick/GitAutoCommittingCherryPickTest.groovy index aed9a9b0f8e7..293a48392cea 100644 --- a/plugins/git4idea/tests/git4idea/cherrypick/GitAutoCommittingCherryPickTest.groovy +++ b/plugins/git4idea/tests/git4idea/cherrypick/GitAutoCommittingCherryPickTest.groovy @@ -16,7 +16,7 @@ package git4idea.cherrypick import com.intellij.notification.NotificationType -import git4idea.history.browser.CherryPicker + import git4idea.history.browser.GitCommit import org.junit.Before import org.junit.Test @@ -25,6 +25,7 @@ import static git4idea.test.MockGit.* import static git4idea.test.MockGit.OperationName.CHERRY_PICK import static git4idea.test.MockGit.OperationName.GET_UNMERGED_FILES import static junit.framework.Assert.assertTrue +import git4idea.history.browser.GitCherryPicker /** * Cherry-pick of one or multiple commits with "commit at once" option enabled. @@ -55,7 +56,7 @@ Otherwise, please use 'git reset' @Before void setUp() { super.setUp() - myCherryPicker = new CherryPicker(myProject, myGit, myPlatformFacade, true) + myCherryPicker = new GitCherryPicker(myProject, myGit, myPlatformFacade, true) } @Test diff --git a/plugins/git4idea/tests/git4idea/cherrypick/GitCherryPickTest.groovy b/plugins/git4idea/tests/git4idea/cherrypick/GitCherryPickTest.groovy index 159828348f8a..82cb52ef6f2a 100644 --- a/plugins/git4idea/tests/git4idea/cherrypick/GitCherryPickTest.groovy +++ b/plugins/git4idea/tests/git4idea/cherrypick/GitCherryPickTest.groovy @@ -23,7 +23,7 @@ import com.intellij.openapi.vcs.changes.LocalChangeList import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.testFramework.vcs.MockChangeListManager import com.intellij.testFramework.vcs.MockContentRevision -import git4idea.history.browser.CherryPicker +import git4idea.history.browser.GitCherryPicker import git4idea.history.browser.GitCommit import git4idea.history.browser.SHAHash import git4idea.history.wholeTree.AbstractHash @@ -37,6 +37,7 @@ import static git4idea.test.MockGit.OperationName.CHERRY_PICK import static git4idea.test.MockGit.commitMessageForCherryPick import static junit.framework.Assert.assertEquals import static junit.framework.Assert.assertTrue +import git4idea.test.TestNotificator /** * Common parent for all tests on cherry-pick @@ -57,9 +58,10 @@ hint: after resolving the conflicts, mark the corrected paths hint: with 'git add ' or 'git rm ' hint: and commit the result with 'git commit' """ - CherryPicker myCherryPicker + GitCherryPicker myCherryPicker GitLightRepository myRepository GitLightRepository.Commit myInitialCommit + TestNotificator myTestNotificator static final LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK = """ @@ -83,6 +85,7 @@ hint: and commit the result with 'git commit' myRepository = new GitLightRepository() myRepositoryManager.add(myRepository) myInitialCommit = myRepository.commit("initial") + myTestNotificator = myPlatformFacade.getNotificator(myProject) as TestNotificator; } GitCommit commit(String commitMessage = "plain commit") { diff --git a/plugins/git4idea/tests/git4idea/cherrypick/GitNotCommittingCherryPickTest.groovy b/plugins/git4idea/tests/git4idea/cherrypick/GitNotCommittingCherryPickTest.groovy index 556bcaa29a68..898318f4ff41 100644 --- a/plugins/git4idea/tests/git4idea/cherrypick/GitNotCommittingCherryPickTest.groovy +++ b/plugins/git4idea/tests/git4idea/cherrypick/GitNotCommittingCherryPickTest.groovy @@ -16,8 +16,9 @@ package git4idea.cherrypick import com.intellij.notification.NotificationType -import git4idea.history.browser.CherryPicker +import git4idea.history.browser.GitCherryPicker import git4idea.history.browser.GitCommit +import git4idea.test.GitLightRepository import git4idea.test.MockGit import git4idea.test.MockVcsHelper import org.junit.Before @@ -25,10 +26,9 @@ import org.junit.Test import static git4idea.test.MockGit.OperationName.CHERRY_PICK import static junit.framework.Assert.* -import git4idea.test.GitLightRepository /** - * Tests for {@link CherryPicker}, when the "auto-commit on cherry-pick" option is deselected. + * Tests for {@link GitCherryPicker}, when the "auto-commit on cherry-pick" option is deselected. * Most situations are equal or similar, so the majority of cherry pick tests are located in {@link GitAutoCommittingCherryPickTest}. * * @author Kirill Likhodedov @@ -38,7 +38,7 @@ class GitNotCommittingCherryPickTest extends GitCherryPickTest { @Before void setUp() { super.setUp() - myCherryPicker = new CherryPicker(myProject, myGit, myPlatformFacade, false) + myCherryPicker = new GitCherryPicker(myProject, myGit, myPlatformFacade, false) } @Test @@ -57,6 +57,50 @@ class GitNotCommittingCherryPickTest extends GitCherryPickTest { // notification is shown from the successful commit, can't check from here } + @Test + void "cancel in commit dialog shouldn't show a notification"() { + GitCommit commit = commit() + + myGit.registerOperationExecutors(new MockGit.SuccessfulCherryPickExecutor(myRepository, commit)) + CancelCommitDialogHandler handler = new CancelCommitDialogHandler() + myVcsHelper.registerHandler(handler) + + invokeCherryPick(commit) + + assertTrue "Commit dialog was not shown", handler.wasCommitDialogShown() + assertNull "Notification should not be shown when cancelling a single commit", myTestNotificator.lastNotification + } + + @Test + void "cancel in 2nd commit dialog after successful commit should shown a notification"() { + GitCommit commit1 = commit() + GitCommit commit2 = commit() + + myGit.registerOperationExecutors(new MockGit.SimpleSuccessOperationExecutor(CHERRY_PICK, ""), + new MockGit.SimpleSuccessOperationExecutor(CHERRY_PICK, "")) + + int dialogNumber = 0; + MockVcsHelper.CommitHandler handler = new MockVcsHelper.CommitHandler() { + boolean commit(String commitMessage) { + dialogNumber++; + // answer OK in the first dialog, Cancel - in the second. + return dialogNumber == 1; + } + } + myVcsHelper.registerHandler(handler) + + invokeCherryPick([commit1, commit2]) + + assertEquals "Commit dialog shown wrong number of times", 2, dialogNumber + assertNotificationShown("Cherry-pick cancelled", + """ + ${commitDetails(commit2)} +


+ However cherry-pick succeeded for the following commit:
+ ${commitDetails(commit1)} + """, NotificationType.WARNING) + } + @Test void "dirty tree, conflicting with commit, then show error"() { myGit.registerOperationExecutors(new MockGit.SimpleErrorOperationExecutor(CHERRY_PICK, LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK)) diff --git a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovycRunner.java b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovycRunner.java index 0d7ac29f4814..4101793b0732 100644 --- a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovycRunner.java +++ b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovycRunner.java @@ -17,10 +17,11 @@ package org.jetbrains.groovy.compiler.rt; import groovy.lang.GroovyClassLoader; import groovyjarjarasm.asm.Opcodes; -import org.codehaus.groovy.ast.AnnotatedNode; -import org.codehaus.groovy.ast.AnnotationNode; -import org.codehaus.groovy.ast.ClassCodeVisitorSupport; -import org.codehaus.groovy.ast.ClassNode; +import org.codehaus.groovy.ast.*; +import org.codehaus.groovy.ast.expr.ConstantExpression; +import org.codehaus.groovy.ast.expr.Expression; +import org.codehaus.groovy.ast.expr.ListExpression; +import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.control.*; import org.codehaus.groovy.control.messages.WarningMessage; @@ -429,6 +430,15 @@ public class GroovycRunner { super.visitClass(node); } + @Override + public void visitField(FieldNode fieldNode) { + Expression valueExpr = fieldNode.getInitialValueExpression(); + if (valueExpr instanceof ConstantExpression && ClassHelper.STRING_TYPE.equals(valueExpr.getType())) { + fieldNode.setInitialValueExpression(new MethodCallExpression(valueExpr, "toString", new ListExpression())); + } + super.visitField(fieldNode); + } + @Override public void visitAnnotations(AnnotatedNode node) { List annotations = node.getAnnotations(); @@ -534,10 +544,6 @@ public class GroovycRunner { ensureWellFormed(field.getGenericType(), visited); } - for (Class inner : aClass.getDeclaredClasses()) { - ensureWellFormed(inner, visited); - } - Type superclass = aClass.getGenericSuperclass(); if (superclass != null) { ensureWellFormed(aClass, visited); diff --git a/plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java b/plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java index 1cb782365946..0f775b2ec4f4 100644 --- a/plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java +++ b/plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java @@ -52,23 +52,23 @@ public class GroovyBuilder extends ModuleLevelBuilder { return ExitCode.NOTHING_DONE; } - String moduleOutput = getModuleOutput(context, chunk); - String compilerOutput = getCompilerOutput(moduleOutput); + Map finalOutputs = getCanonicalModuleOutputs(context, chunk); + Map generationOutputs = getGenerationOutputs(chunk, finalOutputs); final Set toCompilePaths = new LinkedHashSet(); for (File file : toCompile) { toCompilePaths.add(FileUtil.toSystemIndependentName(file.getPath())); } - Map class2Src = buildClassToSourceMap(chunk, context, toCompilePaths, moduleOutput); + Map class2Src = buildClassToSourceMap(chunk, context, toCompilePaths, finalOutputs); final String encoding = context.getProjectDescriptor().getEncodingConfiguration().getPreferredModuleChunkEncoding(chunk); List patchers = Collections.emptyList(); //todo patchers + String compilerOutput = generationOutputs.get(chunk.representativeModule()); final File tempFile = GroovycOSProcessHandler.fillFileWithGroovycParameters( - compilerOutput, toCompilePaths, FileUtil.toSystemDependentName(moduleOutput), class2Src, encoding, patchers + compilerOutput, toCompilePaths, FileUtil.toSystemDependentName(finalOutputs.get(chunk.representativeModule())), class2Src, encoding, patchers ); - //todo different outputs in a chunk //todo xmx final List cmd = ExternalProcessUtil.buildJavaCommandLine( getJavaExecutable(chunk), @@ -98,13 +98,24 @@ public class GroovyBuilder extends ModuleLevelBuilder { } if (myForStubs) { - JavaBuilder.addTempSourcePathRoot(context, new File(compilerOutput)); + for (Module module : generationOutputs.keySet()) { + File root = new File(generationOutputs.get(module)); + context.getRootsIndex().associateRoot(root, module, context.isCompilingTests(), true); + JavaBuilder.addTempSourcePathRoot(context, root); + } } for (CompilerMessage message : handler.getCompilerMessages()) { context.processMessage(message); } - if (!myForStubs && updateDependencies(context, chunk, toCompile, moduleOutput, handler.getSuccessfullyCompiled())) { + + + List compiled = new ArrayList(); + for (GroovycOSProcessHandler.OutputItem item : handler.getSuccessfullyCompiled()) { + compiled.add(ensureCorrectOutput(context, chunk, item, generationOutputs, compilerOutput)); + } + + if (!myForStubs && updateDependencies(context, chunk, toCompile, generationOutputs, compiled)) { return ExitCode.ADDITIONAL_PASS_REQUIRED; } return ExitCode.OK; @@ -114,6 +125,48 @@ public class GroovyBuilder extends ModuleLevelBuilder { } } + private Map getGenerationOutputs(ModuleChunk chunk, Map finalOutputs) throws IOException { + Map generationOutputs = new HashMap(); + for (Module module : chunk.getModules()) { + generationOutputs.put(module, myForStubs ? FileUtil.createTempDirectory("groovyStubs", module.getName()).getPath() : finalOutputs.get(module)); + } + return generationOutputs; + } + + private static Map getCanonicalModuleOutputs(CompileContext context, ModuleChunk chunk) { + Map finalOutputs = new HashMap(); + for (Module module : chunk.getModules()) { + File moduleOutputDir = context.getProjectPaths().getModuleOutputDir(module, context.isCompilingTests()); + assert moduleOutputDir != null; + String moduleOutputPath = FileUtil.toCanonicalPath(moduleOutputDir.getPath()); + assert moduleOutputPath != null; + finalOutputs.put(module, moduleOutputPath.endsWith("/") ? moduleOutputPath : moduleOutputPath + "/"); + } + return finalOutputs; + } + + private static GroovycOSProcessHandler.OutputItem ensureCorrectOutput(CompileContext context, + ModuleChunk chunk, + GroovycOSProcessHandler.OutputItem item, Map generationOutputs, String compilerOutput) throws IOException { + if (chunk.getModules().size() > 1) { + RootDescriptor descriptor = context.getModuleAndRoot(new File(item.sourcePath)); + if (descriptor != null) { + Module srcModule = context.getProject().getModules().get(descriptor.module); + if (srcModule != null && srcModule != chunk.representativeModule()) { + File output = new File(item.outputPath); + + //todo honor package prefixes + File correctRoot = new File(generationOutputs.get(srcModule)); + File correctOutput = new File(correctRoot, FileUtil.getRelativePath(new File(compilerOutput), output)); + + FileUtil.rename(output, correctOutput); + return new GroovycOSProcessHandler.OutputItem(correctOutput.getPath(), item.sourcePath); + } + } + } + return item; + } + private static String getJavaExecutable(ModuleChunk chunk) { Sdk sdk = chunk.getModules().iterator().next().getSdk(); if (sdk instanceof JavaSdk) { @@ -122,23 +175,11 @@ public class GroovyBuilder extends ModuleLevelBuilder { return SystemProperties.getJavaHome() + "/bin/java"; } - private static String getModuleOutput(CompileContext context, ModuleChunk chunk) { - final Module representativeModule = chunk.getModules().iterator().next(); - File moduleOutputDir = context.getProjectPaths().getModuleOutputDir(representativeModule, context.isCompilingTests()); - assert moduleOutputDir != null; - String moduleOutputPath = FileUtil.toCanonicalPath(moduleOutputDir.getPath()); - return moduleOutputPath.endsWith("/") ? moduleOutputPath : moduleOutputPath + "/"; - } - @Override public boolean shouldHonorFileEncodingForCompilation(File file) { return isGroovyFile(file.getAbsolutePath()); } - private String getCompilerOutput(String moduleOutputDir) throws IOException { - return FileUtil.toCanonicalPath((myForStubs ? FileUtil.createTempDirectory("groovyStubs", null) : new File(moduleOutputDir)).getPath()); - } - private static List collectChangedFiles(CompileContext context, ModuleChunk chunk) throws IOException { final List toCompile = new ArrayList(); context.processFilesToRecompile(chunk, new FileProcessor() { @@ -156,7 +197,7 @@ public class GroovyBuilder extends ModuleLevelBuilder { private boolean updateDependencies(CompileContext context, ModuleChunk chunk, List toCompile, - String moduleOutputPath, + Map generationOutputs, List successfullyCompiled) throws IOException { final Mappings delta = context.createDelta(); final List successfullyCompiledFiles = new ArrayList(); @@ -172,11 +213,11 @@ public class GroovyBuilder extends ModuleLevelBuilder { if (moduleAndRoot != null) { final String moduleName = moduleAndRoot.module; context.getDataManager().getSourceToOutputMap(moduleName, moduleAndRoot.isTestRoot).appendData(sourcePath, outputPath); + String moduleOutputPath = generationOutputs.get(context.getProject().getModules().get(moduleName)); + generatedEvent.add(moduleOutputPath, FileUtil.getRelativePath(moduleOutputPath, outputPath, '/')); } callback.associate(outputPath, sourcePath, new ClassReader(FileUtil.loadFileBytes(new File(outputPath)))); successfullyCompiledFiles.add(new File(sourcePath)); - - generatedEvent.add(moduleOutputPath, FileUtil.getRelativePath(moduleOutputPath, outputPath, '/')); } context.processMessage(generatedEvent); @@ -205,9 +246,10 @@ public class GroovyBuilder extends ModuleLevelBuilder { return path.endsWith(".groovy") || path.endsWith(".gpp"); } - private static Map buildClassToSourceMap(ModuleChunk chunk, CompileContext context, Set toCompilePaths, String moduleOutputPath) throws IOException { + private static Map buildClassToSourceMap(ModuleChunk chunk, CompileContext context, Set toCompilePaths, Map finalOutputs) throws IOException { final Map class2Src = new HashMap(); for (Module module : chunk.getModules()) { + String moduleOutputPath = finalOutputs.get(module); final SourceToOutputMapping srcToOut = context.getDataManager().getSourceToOutputMap(module.getName(), context.isCompilingTests()); for (String src : srcToOut.getKeys()) { if (!toCompilePaths.contains(src) && isGroovyFile(src) && diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/unusedDef/UnusedDefInspection.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/unusedDef/UnusedDefInspection.java index 8cd3b620ca1e..b74bd85d7457 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/unusedDef/UnusedDefInspection.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/unusedDef/UnusedDefInspection.java @@ -147,7 +147,7 @@ public class UnusedDefInspection extends GroovyLocalInspectionBase { } } else if (element instanceof GrVariable) { - toHighlight = ((GrVariable)element).getInitializerGroovy(); + toHighlight = ((GrVariable)element).getNameIdentifierGroovy(); } if (toHighlight == null) toHighlight = element; return toHighlight; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyLiteralSelectioner.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyLiteralSelectioner.java index 40997c865382..c2f6ce9b4d45 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyLiteralSelectioner.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyLiteralSelectioner.java @@ -17,14 +17,13 @@ package org.jetbrains.plugins.groovy.editor.selection; import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase; -import com.intellij.lang.ASTNode; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; -import org.jetbrains.plugins.groovy.lang.lexer.TokenSets; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel; +import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl; import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil; import java.util.List; @@ -41,15 +40,9 @@ public class GroovyLiteralSelectioner extends ExtendWordSelectionHandlerBase { } private static boolean isLiteral(PsiElement element) { - if (element instanceof GrListOrMap) return true; - - if (!(element instanceof GrLiteral)) return false; - - ASTNode node = element.getNode(); - if (node == null) return false; - ASTNode firstNode = node.getFirstChildNode(); - final IElementType type = firstNode.getElementType(); - return firstNode == node.getLastChildNode() && TokenSets.STRING_LITERAL_SET.contains(type); + return element instanceof GrListOrMap || + element instanceof GrArgumentLabel || + element instanceof GrLiteralImpl && ((GrLiteralImpl)element).isStringLiteral(); } public List select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/AlignmentProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/AlignmentProvider.java index e484fcc94712..72c4f2ee18f0 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/AlignmentProvider.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/AlignmentProvider.java @@ -17,7 +17,6 @@ package org.jetbrains.plugins.groovy.formatter; import com.intellij.formatting.Alignment; import com.intellij.lang.ASTNode; -import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.PsiElement; import com.intellij.util.containers.hash.HashSet; import org.jetbrains.annotations.NotNull; @@ -32,8 +31,6 @@ import java.util.Set; * @author Max Medvedev */ class AlignmentProvider { - private final static Logger LOG = Logger.getInstance(AlignmentProvider.class); - private final Map> myTree = new HashMap>(); private final Map, Alignment> myAlignments = new HashMap, Alignment>(); private final Map, Boolean> myAllowBackwardShift = new HashMap, Boolean>(); @@ -44,20 +41,20 @@ class AlignmentProvider { } public void addPair(PsiElement e1, PsiElement e2, @Nullable Boolean allowBackwardShift, @Nullable Alignment.Anchor anchor) { - LOG.assertTrue(e1 != e2); + assert e1 != e2; final Set set1 = myTree.get(e1); final Set set2 = myTree.get(e2); if (set1 != null && set2 != null) { - LOG.assertTrue(!myAlignments.containsKey(set1) || !myAlignments.containsKey(set2)); - LOG.assertTrue(myAllowBackwardShift.get(set1).booleanValue() == myAllowBackwardShift.get(set2).booleanValue()); - LOG.assertTrue(myAnchor.get(set1) == myAnchor.get(set2)); + assert (!myAlignments.containsKey(set1) || !myAlignments.containsKey(set2)); + assert(myAllowBackwardShift.get(set1).booleanValue() == myAllowBackwardShift.get(set2).booleanValue()); + assert(myAnchor.get(set1) == myAnchor.get(set2)); if (allowBackwardShift != null) { - LOG.assertTrue(myAllowBackwardShift.get(set1).booleanValue() == allowBackwardShift.booleanValue()); + assert(myAllowBackwardShift.get(set1).booleanValue() == allowBackwardShift.booleanValue()); } if (anchor != null) { - LOG.assertTrue(myAnchor.get(set1) == anchor); + assert(myAnchor.get(set1) == anchor); } if (myAlignments.containsKey(set2)) { @@ -80,19 +77,19 @@ class AlignmentProvider { } else if (set1 != null) { if (allowBackwardShift != null) { - LOG.assertTrue(myAllowBackwardShift.get(set1).booleanValue() == allowBackwardShift.booleanValue()); + assert myAllowBackwardShift.get(set1).booleanValue() == allowBackwardShift.booleanValue(); } if (anchor != null) { - LOG.assertTrue(myAnchor.get(set1) == anchor); + assert myAnchor.get(set1) == anchor; } addInternal(set1, e2); } else if (set2 != null) { if (allowBackwardShift != null) { - LOG.assertTrue(myAllowBackwardShift.get(set2).booleanValue() == allowBackwardShift.booleanValue()); + assert(myAllowBackwardShift.get(set2).booleanValue() == allowBackwardShift.booleanValue()); } if (anchor != null) { - LOG.assertTrue(myAnchor.get(set2) == anchor); + assert(myAnchor.get(set2) == anchor); } addInternal(set2, e1); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/GroovyBlock.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/GroovyBlock.java index ce333f8aab46..32184b90452c 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/GroovyBlock.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/GroovyBlock.java @@ -16,14 +16,12 @@ package org.jetbrains.plugins.groovy.formatter; +import com.intellij.diagnostic.LogMessageEx; import com.intellij.formatting.*; import com.intellij.lang.ASTNode; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.TextRange; -import com.intellij.psi.PsiComment; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiErrorElement; -import com.intellij.psi.PsiWhiteSpace; +import com.intellij.psi.*; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.tree.ILazyParseableElementType; import org.jetbrains.annotations.NotNull; @@ -114,7 +112,8 @@ public class GroovyBlock implements Block, GroovyElementTypes, ASTBlock { mySubBlocks = new GroovyBlockGenerator(this).generateSubBlocks(); } catch (RuntimeException e) { - LOG.error(myNode.getPsi().getContainingFile().getText(), e); + final PsiFile file = myNode.getPsi().getContainingFile(); + LogMessageEx.error(LOG, "Formatting failed for file " + file.getName(), file.getText()); } } return mySubBlocks; diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionConfidence.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionConfidence.java index ededc60a1f96..4df7481c0b13 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionConfidence.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionConfidence.java @@ -19,7 +19,6 @@ import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.util.ThreeState; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.console.GroovyShellAction; import org.jetbrains.plugins.groovy.lang.lexer.TokenSets; import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement; @@ -78,7 +77,7 @@ public class GroovyCompletionConfidence extends CompletionConfidence { @NotNull @Override - public ThreeState shouldSkipAutopopup(@Nullable PsiElement contextElement, @NotNull PsiFile psiFile, int offset) { + public ThreeState shouldSkipAutopopup(@NotNull PsiElement contextElement, @NotNull PsiFile psiFile, int offset) { if (PsiUtil.isLeafElementOfType(contextElement, TokenSets.STRING_LITERALS)) { @SuppressWarnings("ConstantConditions") PsiElement parent = contextElement.getParent(); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java index 5b1c1d9651f6..4ce03ecb8d09 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/CompleteReferenceExpression.java @@ -321,8 +321,7 @@ public class CompleteReferenceExpression { private static Set addAllRestrictedProperties(GrReferenceExpression place) { Set propertyNames = new HashSet(); - final PsiElement qualifier = place.getQualifier(); - if (qualifier == null) { + if (place.getQualifier()==null) { for (GrTypeDefinition containingClass = PsiTreeUtil.getParentOfType(place, GrTypeDefinition.class); containingClass != null; containingClass = PsiTreeUtil.getParentOfType(containingClass, GrTypeDefinition.class)) { @@ -334,6 +333,11 @@ public class CompleteReferenceExpression { return propertyNames; } + private static boolean isMap(GrReferenceExpression place) { + final PsiType qType = GrReferenceResolveUtil.getQualifierType(place); + return InheritanceUtil.isInheritor(qType, CommonClassNames.JAVA_UTIL_MAP); + } + private static class CompleteReferenceProcessor extends ResolverProcessor implements Consumer { private final Consumer myConsumer; private final PrefixMatcher myMatcher; @@ -346,6 +350,7 @@ public class CompleteReferenceExpression { private final Set myProcessedMethodWithOptionalParams = new HashSet(); private final boolean myFieldPointerOperator; private final boolean myMethodPointerOperator; + private final boolean myIsMap; protected CompleteReferenceProcessor(GrReferenceExpression place, Consumer consumer, @NotNull PrefixMatcher matcher, CompletionParameters parameters) { super(null, EnumSet.allOf(ResolveKind.class), place, PsiType.EMPTY_ARRAY); @@ -355,10 +360,11 @@ public class CompleteReferenceExpression { myPreferredFieldNames = addAllRestrictedProperties(place); mySkipPackages = shouldSkipPackages(place); myEventListener = JavaPsiFacade.getInstance(place.getProject()).findClass("java.util.EventListener", place.getResolveScope()); - myPropertyNames.addAll(addAllRestrictedProperties(place)); + myPropertyNames.addAll(myPreferredFieldNames); myFieldPointerOperator = place.hasAt(); myMethodPointerOperator = place.getDotTokenType() == GroovyTokenTypes.mMEMBER_POINTER; + myIsMap = isMap(place); } private static boolean shouldSkipPackages(GrReferenceExpression place) { @@ -438,12 +444,13 @@ public class CompleteReferenceExpression { } private void processPropertyFromField(GrField field, GroovyResolveResult resolveResult) { - if (field.getGetters().length != 0 || field.getSetter() != null || !myPropertyNames.add(field.getName())) return; + if (field.getGetters().length != 0 || field.getSetter() != null || !myPropertyNames.add(field.getName()) || myIsMap) return; myConsumer.consume(((LookupElementBuilder)GroovyCompletionUtil.createCompletionVariant(resolveResult)).withIcon(GroovyIcons.PROPERTY)); } private void processProperty(PsiMethod method, GroovyResolveResult resolveResult) { + if (myIsMap) return; final LookupElementBuilder lookup = createPropertyLookupElement(method, resolveResult, myMatcher); if (lookup != null) { if (myPropertyNames.add(lookup.getLookupString())) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceResolveUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceResolveUtil.java index 3bf45dbbc530..2b4cfd9023d1 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceResolveUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceResolveUtil.java @@ -22,6 +22,7 @@ import com.intellij.psi.util.TypeConversionUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; +import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.api.SpreadState; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; @@ -236,8 +237,8 @@ public class GrReferenceResolveUtil { final GrMember member = PsiTreeUtil.getParentOfType(ref, GrMember.class); if (member == null) { final PsiFile file = ref.getContainingFile(); - assert file instanceof GroovyFile && ((GroovyFile)file).isScript(); - containingClass = ((GroovyFile)file).getScriptClass(); + assert file instanceof GroovyFileBase && ((GroovyFileBase)file).isScript(); + containingClass = ((GroovyFileBase)file).getScriptClass(); } else if (member instanceof GrMethod) { if (!member.hasModifierProperty(PsiModifier.STATIC)) { diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/literals/GrLiteralImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/literals/GrLiteralImpl.java index 623e70b1c6c0..d2428e868418 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/literals/GrLiteralImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/literals/GrLiteralImpl.java @@ -160,7 +160,7 @@ public class GrLiteralImpl extends GrAbstractLiteral implements GrLiteral, PsiLa if (child == null) return false; IElementType elementType = child.getNode().getElementType(); - return elementType == mGSTRING_LITERAL || elementType == mSTRING_LITERAL; + return TokenSets.STRING_LITERAL_SET.contains(elementType); } @NotNull diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyNameSuggestionUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyNameSuggestionUtil.java index c001c78bfdf7..c23bd1bdf594 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyNameSuggestionUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyNameSuggestionUtil.java @@ -126,7 +126,7 @@ public class GroovyNameSuggestionUtil { private static void generateNameByString(Set possibleNames, String value, boolean forStaticVariable, Project project) { if (!JavaPsiFacade.getInstance(project).getNameHelper().isIdentifier(value)) return; if (forStaticVariable) { - StringBuffer buffer = new StringBuffer(value.length() + 10); + StringBuilder buffer = new StringBuilder(value.length() + 10); char[] chars = new char[value.length()]; value.getChars(0, value.length(), chars, 0); boolean wasLow = Character.isLowerCase(chars[0]); diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyActionsTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyActionsTest.groovy index fabf90f28352..4e1574c262b5 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyActionsTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/GroovyActionsTest.groovy @@ -43,6 +43,9 @@ public class GroovyActionsTest extends LightCodeInsightFixtureTestCase { public void testSWInGString4() throws Exception {doTestForSelectWord(4);} public void testSWInGString5() throws Exception {doTestForSelectWord(5);} public void testSWInParameterList() throws Exception {doTestForSelectWord(3);} + public void testSWInArgLabel1() {doTestForSelectWord(2)} + public void testSWInArgLabel2() {doTestForSelectWord(2)} + public void testSWInArgLabel3() {doTestForSelectWord(2)} public void testSWListLiteralArgument() throws Exception { doTestForSelectWord 2, diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTest.groovy index d2ee4fc4125e..f7d020fb394b 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTest.groovy @@ -567,6 +567,42 @@ class Main { assertEmpty make() } + public void "test module cycle"() { + def dep = addDependentModule() + PsiTestUtil.addDependency(myModule, dep) + addGroovyLibrary(dep) + + myFixture.addFileToProject('Foo.groovy', 'class Foo extends Bar { static void main(String[] args) { println "Hello from Foo" } }') + myFixture.addFileToProject('FooX.java', 'class FooX extends Bar { }') + myFixture.addFileToProject("dependent/Bar.groovy", "class Bar { Foo f; static void main(String[] args) { println 'Hello from Bar' } }") + myFixture.addFileToProject("dependent/BarX.java", "class BarX { Foo f; }") + + def checkClassFiles = { + assert findClassFile('Foo', myModule) + assert findClassFile('FooX', myModule) + assert findClassFile('Bar', dep) + assert findClassFile('BarX', dep) + + assert !findClassFile('Bar', myModule) + assert !findClassFile('BarX', myModule) + assert !findClassFile('Foo', dep) + assert !findClassFile('FooX', dep) + } + + println '1' + println make().join('\n') + checkClassFiles() + + println '2' + println make().join('\n') + checkClassFiles() + + assertOutput('Foo', 'Hello from Foo', myModule) + assertOutput('Bar', 'Hello from Bar', dep) + + checkClassFiles() + } + public void testCompileTimeConstants() { myFixture.addFileToProject 'Gr.groovy', ''' interface Gr { @@ -629,6 +665,35 @@ public class Main { assert findClassFile("Client") } + public void "test ignore groovy internal non-existent interface helper inner class"() { + myFixture.addFileToProject 'Foo.groovy', ''' +interface Foo {} + +class Zoo { + Foo foo() {} + static class Inner implements Foo {} +} + +''' + def bar = myFixture.addFileToProject('Bar.groovy', 'class Bar { def foo = new Zoo.Inner() {} }') + + assertEmpty make() + assertEmpty compileFiles(bar.virtualFile) + } + + public void "test multiline strings"() { + myFixture.addFileToProject 'Foo.groovy', '''class Foo { + public static final String s = """ +multi +line +string +""" + } ''' + myFixture.addFileToProject 'Bar.java', 'class Bar extends Foo {} ' + + assertEmpty make() + } + public static class IdeaModeTest extends GroovyCompilerTest { @Override protected boolean useJps() { false } } diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java index 304540b8e427..d3109934d310 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java @@ -51,6 +51,7 @@ import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiFile; +import com.intellij.testFramework.IdeaTestUtil; import com.intellij.testFramework.PsiTestUtil; import com.intellij.testFramework.builders.JavaModuleFixtureBuilder; import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase; @@ -184,8 +185,10 @@ public abstract class GroovyCompilerTestCase extends JavaCodeInsightFixtureTestC final ContentEntry entry = model.addContentEntry(depRoot); entry.addSourceFolder(depRoot, false); model.setSdk(ModuleRootManager.getInstance(myModule).getSdk()); - model.commit(); + + IdeaTestUtil.setModuleLanguageLevel(dep, LanguageLevelModuleExtension.getInstance(myModule).getLanguageLevel()); + result.setResult(dep); } }.execute().getResultObject(); @@ -208,9 +211,15 @@ public abstract class GroovyCompilerTestCase extends JavaCodeInsightFixtureTestC } @Nullable protected VirtualFile findClassFile(String className) { - final CompilerModuleExtension extension = ModuleRootManager.getInstance(myModule).getModuleExtension(CompilerModuleExtension.class); + return findClassFile(className, myModule); + } + @Nullable protected VirtualFile findClassFile(String className, Module module) { //noinspection ConstantConditions - return extension.getCompilerOutputPath().findChild(className + ".class"); + VirtualFile path = ModuleRootManager.getInstance(module).getModuleExtension(CompilerModuleExtension.class).getCompilerOutputPath(); + path.getChildren(); + assert path != null; + path.refresh(false, true); + return path.findChild(className + ".class"); } protected static void touch(VirtualFile file) throws IOException { diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/GroovyCompletionTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/GroovyCompletionTest.groovy index fbfd5b92c939..42bf94b12d2f 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/GroovyCompletionTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/GroovyCompletionTest.groovy @@ -1317,4 +1317,13 @@ def foo(List> list)'''); myFixture.complete(CompletionType.BASIC); assertOrderedEquals(myFixture.lookupElementStrings, "extends", "super"); } + + void testMapDontCompleteProperties() { + myFixture.configureByText("_.groovy", '''\ +def map = [1:2] +print map.metc +'''); + myFixture.complete(CompletionType.BASIC); + assertEmpty myFixture.getLookupElements() + } } \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/actions/SWInArgLabel1.groovy b/plugins/groovy/testdata/groovy/actions/SWInArgLabel1.groovy new file mode 100644 index 000000000000..1330bcad2644 --- /dev/null +++ b/plugins/groovy/testdata/groovy/actions/SWInArgLabel1.groovy @@ -0,0 +1 @@ +print('ghj ghj ghj':fg) diff --git a/plugins/groovy/testdata/groovy/actions/SWInArgLabel1_after.groovy b/plugins/groovy/testdata/groovy/actions/SWInArgLabel1_after.groovy new file mode 100644 index 000000000000..3c1158d66da3 --- /dev/null +++ b/plugins/groovy/testdata/groovy/actions/SWInArgLabel1_after.groovy @@ -0,0 +1 @@ +print('ghj ghj ghj':fg) diff --git a/plugins/groovy/testdata/groovy/actions/SWInArgLabel2.groovy b/plugins/groovy/testdata/groovy/actions/SWInArgLabel2.groovy new file mode 100644 index 000000000000..fe8723cb220b --- /dev/null +++ b/plugins/groovy/testdata/groovy/actions/SWInArgLabel2.groovy @@ -0,0 +1 @@ +print(/ghj ghj ghj/:fg) \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/actions/SWInArgLabel2_after.groovy b/plugins/groovy/testdata/groovy/actions/SWInArgLabel2_after.groovy new file mode 100644 index 000000000000..edfa0b9f5471 --- /dev/null +++ b/plugins/groovy/testdata/groovy/actions/SWInArgLabel2_after.groovy @@ -0,0 +1 @@ +print(/ghj ghj ghj/:fg) \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/actions/SWInArgLabel3.groovy b/plugins/groovy/testdata/groovy/actions/SWInArgLabel3.groovy new file mode 100644 index 000000000000..7d113b159fea --- /dev/null +++ b/plugins/groovy/testdata/groovy/actions/SWInArgLabel3.groovy @@ -0,0 +1 @@ +print($/ghj ghj ghj/$:fg) \ No newline at end of file diff --git a/plugins/groovy/testdata/groovy/actions/SWInArgLabel3_after.groovy b/plugins/groovy/testdata/groovy/actions/SWInArgLabel3_after.groovy new file mode 100644 index 000000000000..208addaa1f78 --- /dev/null +++ b/plugins/groovy/testdata/groovy/actions/SWInArgLabel3_after.groovy @@ -0,0 +1 @@ +print($/ghj ghj ghj/$:fg) \ No newline at end of file diff --git a/plugins/groovy/testdata/highlighting/DefinitionUsedInSwitchCase.groovy b/plugins/groovy/testdata/highlighting/DefinitionUsedInSwitchCase.groovy index db5b2008f5c6..fe8d767a51a1 100644 --- a/plugins/groovy/testdata/highlighting/DefinitionUsedInSwitchCase.groovy +++ b/plugins/groovy/testdata/highlighting/DefinitionUsedInSwitchCase.groovy @@ -14,7 +14,7 @@ * limitations under the License. */ def m = [a: 1, b: 2] -def m1 = [a: 1, b: 2] +def m1 = [a: 1, b: 2] def val = 'a' switch (val) { diff --git a/plugins/groovy/testdata/highlighting/IfIncrementElseReturn.groovy b/plugins/groovy/testdata/highlighting/IfIncrementElseReturn.groovy index db5b2008f5c6..fe8d767a51a1 100644 --- a/plugins/groovy/testdata/highlighting/IfIncrementElseReturn.groovy +++ b/plugins/groovy/testdata/highlighting/IfIncrementElseReturn.groovy @@ -14,7 +14,7 @@ * limitations under the License. */ def m = [a: 1, b: 2] -def m1 = [a: 1, b: 2] +def m1 = [a: 1, b: 2] def val = 'a' switch (val) { diff --git a/plugins/groovy/testdata/highlighting/SwitchControlFlow.groovy b/plugins/groovy/testdata/highlighting/SwitchControlFlow.groovy index bd45c16a39d4..75f8b63eccc8 100644 --- a/plugins/groovy/testdata/highlighting/SwitchControlFlow.groovy +++ b/plugins/groovy/testdata/highlighting/SwitchControlFlow.groovy @@ -16,7 +16,7 @@ def testV(def variable) { def v = "s" def m="10" - def x="10" + def x="10" try { switch (variable) { case 1: diff --git a/plugins/groovy/testdata/highlighting/UnusedVariable.groovy b/plugins/groovy/testdata/highlighting/UnusedVariable.groovy index d4b0eb0364cb..6e67c62fba3e 100644 --- a/plugins/groovy/testdata/highlighting/UnusedVariable.groovy +++ b/plugins/groovy/testdata/highlighting/UnusedVariable.groovy @@ -13,4 +13,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -Class clazz = null \ No newline at end of file +Class clazz = null \ No newline at end of file diff --git a/plugins/groovy/testdata/highlighting/UsageInInjection.groovy b/plugins/groovy/testdata/highlighting/UsageInInjection.groovy index 5840ca40e0e8..3b0f5436015a 100644 --- a/plugins/groovy/testdata/highlighting/UsageInInjection.groovy +++ b/plugins/groovy/testdata/highlighting/UsageInInjection.groovy @@ -15,6 +15,6 @@ */ def x = new Date() def y = new Date() -def z = new Date() +def z = new Date() assert false : "should have thrown exception, but returned $x" assert false : "should have thrown exception, but returned ${y}" \ No newline at end of file diff --git a/plugins/groovy/testdata/highlighting/VeryLongDfaWithComplexGenerics.groovy b/plugins/groovy/testdata/highlighting/VeryLongDfaWithComplexGenerics.groovy index 1d67e40d8e71..952de9bdc403 100644 --- a/plugins/groovy/testdata/highlighting/VeryLongDfaWithComplexGenerics.groovy +++ b/plugins/groovy/testdata/highlighting/VeryLongDfaWithComplexGenerics.groovy @@ -19,7 +19,7 @@ class TroubleCase { private Foo fooBaz; private void troubleMethod(boolean b) { - def icDao = (b?fooBaz:fooBar); + def icDao = (b?fooBaz:fooBar); for(Object x: new ArrayList()) { } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorHolder.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorHolder.java index 5f4cf19f3724..a453fac165e7 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorHolder.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenDomElementDescriptorHolder.java @@ -41,7 +41,7 @@ import java.net.URL; import java.util.Map; public class MavenDomElementDescriptorHolder { - private static final Logger LOG = Logger.getInstance("#org.jetbrains.idea.maven.dom.MavenDomElementDescriptorHolder"); + private static final Logger LOG = Logger.getInstance(MavenDomElementDescriptorHolder.class); private enum FileKind { PROJECT_FILE { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java index c4ac16e22f89..6371106883f2 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java @@ -49,7 +49,7 @@ import java.util.Set; */ public class MavenResumeAction extends AnAction { - private static final Logger LOG = Logger.getInstance("#org.jetbrains.idea.maven.execution.MavenResumeAction"); + private static final Logger LOG = Logger.getInstance(MavenResumeAction.class); private static final Set PARAMS_DISABLING_RESUME = CollectionFactory.newSet("-rf", "-resume-from", "-pl", "-projects", "-am", "-also-make", "-amd", "-also-make-dependents"); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java index 2496bfeff445..c92a70804daf 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunner.java @@ -40,7 +40,7 @@ import java.util.List; @State(name = "MavenRunner", storages = {@Storage( file = StoragePathMacros.WORKSPACE_FILE)}) public class MavenRunner implements PersistentStateComponent { - private static final Logger LOG = Logger.getInstance("#org.jetbrains.idea.maven.execution.MavenRunner"); + private static final Logger LOG = Logger.getInstance(MavenRunner.class); private MavenRunnerSettings mySettings = new MavenRunnerSettings(); private final Project myProject; diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenDefaultModifiableModelsProvider.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenDefaultModifiableModelsProvider.java index f9af5a08c854..81ddd7cbdc2b 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenDefaultModifiableModelsProvider.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenDefaultModifiableModelsProvider.java @@ -118,6 +118,9 @@ public class MavenDefaultModifiableModelsProvider extends MavenBaseModifiableMod Collection rootModels = myRootModels.values(); ModifiableRootModel[] rootModels1 = rootModels.toArray(new ModifiableRootModel[rootModels.size()]); + for (ModifiableRootModel model : rootModels1) { + assert !model.isDisposed() : "Already disposed: " + model; + } ModifiableModelCommitter.multiCommit(rootModels1, myModuleModel); for (ModifiableFacetModel each : myFacetModels.values()) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java index 4b11cb43148b..8379f2ea32eb 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java @@ -158,8 +158,6 @@ public class MavenModuleImporter { private void configLanguageLevel() { final LanguageLevel level = LanguageLevel.parse(myMavenProject.getSourceLevel()); - if (level != null) { - myRootModelAdapter.setLanguageLevel(level); - } + myRootModelAdapter.setLanguageLevel(level); } } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java index 56f965a00cb9..f4ff8d86fe24 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.java @@ -15,6 +15,8 @@ */ package org.jetbrains.idea.maven.importing; +import com.intellij.compiler.CompilerConfiguration; +import com.intellij.compiler.CompilerConfigurationImpl; import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.*; @@ -102,7 +104,6 @@ public class MavenProjectImporter { hasChanges = true; importModules(postTasks); scheduleRefreshResolvedArtifacts(postTasks); - configSettings(); } if (projectsHaveChanges || myImportModuleGroupsRequired) { @@ -118,6 +119,10 @@ public class MavenProjectImporter { if (hasChanges) { myModelsProvider.commit(); + + if (projectsHaveChanges) { + configSettings(); + } } else { myModelsProvider.dispose(); @@ -368,51 +373,28 @@ public class MavenProjectImporter { private void configSettings() { MavenUtil.invokeAndWaitWriteAction(myProject, new Runnable() { public void run() { - String level = calcTargetLevel(); - if (level == null) return; + CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject); - String options = JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING; - Pattern pattern = Pattern.compile("(-target (\\S+))"); - Matcher matcher = pattern.matcher(options); + MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(myProject); - if (matcher.find()) { - String currentValue = MavenProject.normalizeCompilerLevel(matcher.group(2)); + for (MavenProject project : myAllProjects) { + String targetLevel = project.getTargetLevel(); - if (currentValue == null || compareCompilerLevel(level, currentValue) < 0) { - StringBuffer buffer = new StringBuffer(); - matcher.appendReplacement(buffer, "-target " + level); - matcher.appendTail(buffer); - options = buffer.toString(); + if (targetLevel != null) { + Module module = projectsManager.findModule(project); + if (module != null) { + configuration.setBytecodeTargetLevel(module, targetLevel); + } } } - else { - if (!StringUtil.isEmptyOrSpaces(options)) options += " "; - options += "-target " + level; - } + + String options = JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING; + options = options.replaceFirst("(-target (\\S+))", ""); // Old IDEAs saved JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING = options; } }); } - private String calcTargetLevel() { - String maxSource = null; - String minTarget = null; - for (MavenProject each : myAllProjects) { - String source = each.getSourceLevel(); - String target = each.getTargetLevel(); - if (source != null && (maxSource == null || compareCompilerLevel(maxSource, source) < 0)) maxSource = source; - if (target != null && (minTarget == null || compareCompilerLevel(minTarget, target) > 0)) minTarget = target; - } - return (maxSource != null && compareCompilerLevel(minTarget, maxSource) < 0) ? maxSource : minTarget; - } - - private int compareCompilerLevel(String left, String right) { - if (left == null && right == null) return 0; - if (left == null) return -1; - if (right == null) return 1; - return left.compareTo(right); - } - private void importModules(final List postTasks) { Map projectsWithChanges = myProjectsToImportWithChanges; Set projects = projectsWithChanges.keySet(); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java index adee4cf84848..be944b5ff8fd 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java @@ -114,8 +114,7 @@ public class MavenRootModelAdapter { Url url = toUrl(path); ContentEntry e = getContentRootFor(url); if (e == null) return; - unregisterAll(path, true, true - ); + unregisterAll(path, true, true); unregisterAll(path, false, true); e.addSourceFolder(url.getUrl(), testSource); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenMergingUpdateQueue.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenMergingUpdateQueue.java index 83a708c1147f..23229ede46c9 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenMergingUpdateQueue.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenMergingUpdateQueue.java @@ -38,7 +38,7 @@ import java.util.concurrent.atomic.AtomicInteger; public class MavenMergingUpdateQueue extends MergingUpdateQueue { - private static final Logger LOG = Logger.getInstance("#org.jetbrains.idea.maven.utils.MavenMergingUpdateQueue"); + private static final Logger LOG = Logger.getInstance(MavenMergingUpdateQueue.class); private final AtomicInteger mySuspendCounter = new AtomicInteger(0); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/StructureImportingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/StructureImportingTest.java index aa5b2fe25357..05fb75491978 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/StructureImportingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/StructureImportingTest.java @@ -15,9 +15,11 @@ */ package org.jetbrains.idea.maven.importing; +import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; +import com.intellij.openapi.module.Module; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.LanguageLevelModuleExtension; import com.intellij.openapi.roots.ModuleRootManager; @@ -836,7 +838,7 @@ public class StructureImportingTest extends MavenImportingTestCase { } public void testSettingTargetLevel() throws Exception { - JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING = "-Xmm500m -Xms128m"; + JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING = "-Xmm500m -Xms128m -target 1.5"; importProject("test" + "project" + @@ -853,31 +855,16 @@ public class StructureImportingTest extends MavenImportingTestCase { " " + ""); - assertEquals("-Xmm500m -Xms128m -target 1.3", JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING); + assertEquals("-Xmm500m -Xms128m", JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING.trim()); + + Module module = getModule("project"); + + String targetLevel = CompilerConfiguration.getInstance(myProject).getBytecodeTargetLevel(module); + + assertEquals("1.3", targetLevel); } - public void testRewritingTargetLevel() throws Exception { - JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING = "-Xmm500m -target 1.5 -Xms128m"; - - importProject("test" + - "project" + - "1" + - - "" + - " " + - " " + - " maven-compiler-plugin" + - " " + - " 1.3" + - " " + - " " + - " " + - ""); - - assertEquals("-Xmm500m -target 1.3 -Xms128m", JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING); - } - - public void testSettingTargetLevelAtMinimalSpecified() throws Exception { + public void testSettingTargetLevelFromParent() throws Exception { createProjectPom("test" + "project" + "pom" + @@ -886,27 +873,32 @@ public class StructureImportingTest extends MavenImportingTestCase { "" + " m1" + " m2" + - ""); + "" + + + "" + + "1.3" + + ""); createModulePom("m1", "test" + "m1" + "1" + - "" + - " " + - " " + - " maven-compiler-plugin" + - " " + - " 1.3" + - " " + - " " + - " " + - ""); + "" + + "test" + + "project" + + "1" + + ""); createModulePom("m2", "test" + "m2" + "1" + + "" + + "test" + + "project" + + "1" + + "" + + "" + " " + " " + @@ -920,76 +912,9 @@ public class StructureImportingTest extends MavenImportingTestCase { importProject(); - assertEquals("-target 1.3", JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING); - } - - public void testSettingTargetLevelAtMinimalSpecifiedButNoLessThanMaximumSourceLevel() throws Exception { - createProjectPom("test" + - "project" + - "pom" + - "1" + - - "" + - " m1" + - " m2" + - ""); - - createModulePom("m1", "test" + - "m1" + - "1" + - - "" + - " " + - " " + - " maven-compiler-plugin" + - " " + - " 1.3" + - " 1.3" + - " " + - " " + - " " + - ""); - - createModulePom("m2", "test" + - "m2" + - "1" + - - "" + - " " + - " " + - " maven-compiler-plugin" + - " " + - " 1.5" + - " 1.5" + - " " + - " " + - " " + - ""); - - importProject(); - - assertEquals("-target 1.5", JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING); - } - - public void testRewritingIncorrectTargetLevel() throws Exception { - JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING = "-Xmm500m -target ${undefined.variable} -Xms128m"; - - importProject("test" + - "project" + - "1" + - - "" + - " " + - " " + - " maven-compiler-plugin" + - " " + - " 1.3" + - " " + - " " + - " " + - ""); - - assertEquals("-Xmm500m -target 1.3 -Xms128m", JavacSettings.getInstance(myProject).ADDITIONAL_OPTIONS_STRING); + assertEquals("1.3", CompilerConfiguration.getInstance(myProject).getBytecodeTargetLevel(getModule("project"))); + assertEquals("1.3", CompilerConfiguration.getInstance(myProject).getBytecodeTargetLevel(getModule("m1"))); + assertEquals("1.5", CompilerConfiguration.getInstance(myProject).getBytecodeTargetLevel(getModule("m2"))); } public void testProjectWithBuiltExtension() throws Exception { diff --git a/plugins/properties/src/com/intellij/lang/properties/xml/SoftLazyValue.java b/plugins/properties/src/com/intellij/lang/properties/xml/SoftLazyValue.java new file mode 100644 index 000000000000..237e4276e818 --- /dev/null +++ b/plugins/properties/src/com/intellij/lang/properties/xml/SoftLazyValue.java @@ -0,0 +1,41 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.lang.properties.xml; + +import org.jetbrains.annotations.NotNull; + +import java.lang.ref.SoftReference; + +/** + * @author Dmitry Avdeev + * Date: 5/25/12 + */ +public abstract class SoftLazyValue { + + private SoftReference myReference; + + public T getValue() { + T t; + if (myReference == null || (t = myReference.get()) == null) { + t = compute(); + myReference = new SoftReference(t); + } + return t; + } + + @NotNull + protected abstract T compute(); +} diff --git a/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesFile.java b/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesFile.java index 14ac2f4629ea..91fb1fe96673 100644 --- a/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesFile.java +++ b/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesFile.java @@ -33,8 +33,25 @@ public class XmlPropertiesFile implements PropertiesFile { private static final Key> KEY = Key.create("xml properties file"); private final XmlFile myFile; - private final List myProperties = new ArrayList(); - private final MultiMap myPropertiesMap = new MultiMap(); + private final SoftLazyValue> myPropertiesMap = new SoftLazyValue>() { + @NotNull + @Override + protected MultiMap compute() { + XmlTag rootTag = myFile.getRootTag(); + if (rootTag == null) { + return MultiMap.emptyInstance(); + } + + XmlTag[] entries = rootTag.findSubTags("entry"); + MultiMap map = new MultiMap(); + + for (XmlTag entry : entries) { + XmlProperty property = new XmlProperty(entry, XmlPropertiesFile.this); + map.putValue(property.getKey(), property); + } + return map; + } + }; @Nullable public static PropertiesFile getPropertiesFile(final PsiFile file) { @@ -55,15 +72,6 @@ public class XmlPropertiesFile implements PropertiesFile { private XmlPropertiesFile(XmlFile file) { myFile = file; - XmlTag rootTag = file.getRootTag(); - if (rootTag != null) { - XmlTag[] entries = rootTag.findSubTags("entry"); - for (XmlTag entry : entries) { - XmlProperty property = new XmlProperty(entry, this); - myProperties.add(property); - myPropertiesMap.putValue(property.getKey(), property); - } - } } @NotNull @@ -75,19 +83,19 @@ public class XmlPropertiesFile implements PropertiesFile { @NotNull @Override public List getProperties() { - return myProperties; + return new ArrayList(myPropertiesMap.getValue().values()); } @Override public IProperty findPropertyByKey(@NotNull @NonNls String key) { - Collection properties = myPropertiesMap.get(key); + Collection properties = myPropertiesMap.getValue().get(key); return properties.isEmpty() ? null : properties.iterator().next(); } @NotNull @Override public List findPropertiesByKey(@NotNull @NonNls String key) { - return new ArrayList(myPropertiesMap.get(key)); + return new ArrayList(myPropertiesMap.getValue().get(key)); } @NotNull diff --git a/plugins/svn4idea/lib/svnkit-javahl.jar b/plugins/svn4idea/lib/svnkit-javahl.jar index b19c1cef3f55..2520dabae9bc 100644 Binary files a/plugins/svn4idea/lib/svnkit-javahl.jar and b/plugins/svn4idea/lib/svnkit-javahl.jar differ diff --git a/plugins/svn4idea/lib/svnkit-javahl16.zip b/plugins/svn4idea/lib/svnkit-javahl16.zip index fe72b72541ff..a2fb51df6e94 100644 Binary files a/plugins/svn4idea/lib/svnkit-javahl16.zip and b/plugins/svn4idea/lib/svnkit-javahl16.zip differ diff --git a/plugins/svn4idea/lib/svnkit.jar b/plugins/svn4idea/lib/svnkit.jar index 436aff99484d..eb1f47d6a482 100644 Binary files a/plugins/svn4idea/lib/svnkit.jar and b/plugins/svn4idea/lib/svnkit.jar differ diff --git a/plugins/svn4idea/lib/svnkitsrc.zip b/plugins/svn4idea/lib/svnkitsrc.zip index f5992f24a3e3..87949bb3907c 100644 Binary files a/plugins/svn4idea/lib/svnkitsrc.zip and b/plugins/svn4idea/lib/svnkitsrc.zip differ diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangeProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangeProvider.java index d8be7a591bc5..f2c3f700b33e 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangeProvider.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangeProvider.java @@ -15,6 +15,7 @@ */ package org.jetbrains.idea.svn; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; @@ -22,6 +23,7 @@ import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Comparing; +import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.actions.VcsContextFactory; @@ -99,7 +101,7 @@ public class SvnChangeProvider implements ChangeProvider { processFile(path, context, status, false, context.getClient()); }*/ - processCopiedAndDeleted(context); + processCopiedAndDeleted(context, dirtyScope); processUnsaved(dirtyScope, addGate, context); mySvnFileUrlMapping.acceptNestedData(nestedCopiesBuilder.getSet()); @@ -146,12 +148,12 @@ public class SvnChangeProvider implements ChangeProvider { }; } - private void processCopiedAndDeleted(final SvnChangeProviderContext context) throws SVNException { + private void processCopiedAndDeleted(final SvnChangeProviderContext context, final VcsDirtyScope dirtyScope) throws SVNException { for(SvnChangedFile copiedFile: context.getCopiedFiles()) { if (context.isCanceled()) { throw new ProcessCanceledException(); } - processCopiedFile(copiedFile, context.getBuilder(), context); + processCopiedFile(copiedFile, context.getBuilder(), context, dirtyScope); } for(SvnChangedFile deletedFile: context.getDeletedFiles()) { if (context.isCanceled()) { @@ -166,7 +168,7 @@ public class SvnChangeProvider implements ChangeProvider { final StatusWalkerPartnerImpl partner = new StatusWalkerPartnerImpl(myVcs, ProgressManager.getInstance().getProgressIndicator()); final SvnRecursiveStatusWalker walker = new SvnRecursiveStatusWalker(myVcs.getProject(), context, partner); walker.go(path, recursive ? SVNDepth.INFINITY : SVNDepth.IMMEDIATES); - processCopiedAndDeleted(context); + processCopiedAndDeleted(context, null); } @Nullable @@ -183,7 +185,7 @@ public class SvnChangeProvider implements ChangeProvider { private void processCopiedFile(SvnChangedFile copiedFile, ChangelistBuilder builder, - SvnChangeProviderContext context) throws SVNException { + SvnChangeProviderContext context, final VcsDirtyScope dirtyScope) throws SVNException { boolean foundRename = false; final SVNStatus copiedStatus = copiedFile.getStatus(); final String copyFromURL = copiedFile.getCopyFromURL(); @@ -206,11 +208,10 @@ public class SvnChangeProvider implements ChangeProvider { final SVNStatus deletedStatus = deletedFile.getStatus(); if ((deletedStatus != null) && (deletedStatus.getURL() != null) && Comparing.equal(copyFromURL, deletedStatus.getURL().toString())) { final String clName = changeListNameFromStatus(copiedFile.getStatus()); - builder.removeRegisteredChangeFor(copiedFile.getFilePath()); - builder.processChangeInList(context.createMovedChange(createBeforeRevision(deletedFile, true), - CurrentContentRevision.create(copiedFile.getFilePath()), copiedStatus, deletedStatus), clName, SvnVcs - .getKey()); - deletedToDelete.add(deletedFile); + final Change newChange = context.createMovedChange(createBeforeRevision(deletedFile, true), + CurrentContentRevision.create(copiedFile.getFilePath()), copiedStatus, + deletedStatus); + applyMovedChange(copiedFile.getFilePath(), builder, dirtyScope, deletedToDelete, deletedFile, clName, newChange); for(Iterator iterChild = context.getDeletedFiles().iterator(); iterChild.hasNext();) { SvnChangedFile deletedChild = iterChild.next(); final SVNStatus childStatus = deletedChild.getStatus(); @@ -227,11 +228,10 @@ public class SvnChangeProvider implements ChangeProvider { File newPath = new File(copiedFile.getFilePath().getIOFile(), relativePath); FilePath newFilePath = myFactory.createFilePathOn(newPath); if (!context.isDeleted(newFilePath)) { - builder.removeRegisteredChangeFor(newFilePath); - builder.processChangeInList(context.createMovedChange(createBeforeRevision(deletedChild, true), - CurrentContentRevision.create(newFilePath), - context.getTreeConflictStatus(newPath), childStatus), clName, SvnVcs.getKey()); - deletedToDelete.add(deletedChild); + final Change movedChange = context.createMovedChange(createBeforeRevision(deletedChild, true), + CurrentContentRevision.create(newFilePath), + context.getTreeConflictStatus(newPath), childStatus); + applyMovedChange(newFilePath, builder, dirtyScope, deletedToDelete, deletedChild, clName, movedChange); } } } @@ -273,6 +273,23 @@ public class SvnChangeProvider implements ChangeProvider { } } + private void applyMovedChange(final FilePath oldPath, + ChangelistBuilder builder, + final VcsDirtyScope dirtyScope, + Set deletedToDelete, SvnChangedFile deletedFile, String clName, final Change newChange) { + final boolean isUnder = dirtyScope == null ? true : ApplicationManager.getApplication().runReadAction(new Computable() { + @Override + public Boolean compute() { + return ChangeListManagerImpl.isUnder(newChange, dirtyScope); + } + }); + if (isUnder) { + builder.removeRegisteredChangeFor(oldPath); + builder.processChangeInList(newChange, clName, SvnVcs.getKey()); + deletedToDelete.add(deletedFile); + } + } + private SvnContentRevision createBeforeRevision(final SvnChangedFile changedFile, final boolean forDeleted) { return SvnContentRevision.createBaseRevision(myVcs, forDeleted ? FilePathImpl.createForDeletedFile(changedFile.getStatus().getFile(), diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangelistListener.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangelistListener.java index da8ef1c3cd8f..ef6f4e99ecda 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangelistListener.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangelistListener.java @@ -41,11 +41,13 @@ public class SvnChangelistListener implements ChangeListListener { private final static Logger LOG = Logger.getInstance("#org.jetbrains.idea.svn.SvnChangelistListener"); private final Project myProject; - private final SVNChangelistClient myClient; + private final SvnVcs myVcs; + //private final SVNChangelistClient myClient; - public SvnChangelistListener(final Project project, final SVNChangelistClient client) { + public SvnChangelistListener(final Project project, final SvnVcs vcs) { myProject = project; - myClient = client; + myVcs = vcs; + //myClient = client; } public void changeListAdded(final ChangeList list) { @@ -59,7 +61,7 @@ public class SvnChangelistListener implements ChangeListListener { final List paths = getPathsFromChanges(changes); for (String path : paths) { try { - myClient.doRemoveFromChangelist(new File[]{new File(path)}, SVNDepth.EMPTY, null); + myVcs.createChangelistClient().doRemoveFromChangelist(new File[]{new File(path)}, SVNDepth.EMPTY, null); } catch (SVNException e) { LOG.info(e); @@ -75,7 +77,7 @@ public class SvnChangelistListener implements ChangeListListener { final List paths = getPathsFromChanges(changes); for (String path : paths) { try { - myClient.doAddToChangelist(new File[]{new File(path)}, SVNDepth.EMPTY, toList.getName(), null); + myVcs.createChangelistClient().doAddToChangelist(new File[]{new File(path)}, SVNDepth.EMPTY, toList.getName(), null); } catch (SVNException e) { LOG.info(e); @@ -87,7 +89,7 @@ public class SvnChangelistListener implements ChangeListListener { final List paths = getPathsFromChanges(list.getChanges()); for (String path : paths) { try { - myClient.doRemoveFromChangelist(new File[]{new File(path)}, SVNDepth.EMPTY, null); + myVcs.createChangelistClient().doRemoveFromChangelist(new File[]{new File(path)}, SVNDepth.EMPTY, null); } catch (SVNException e) { LOG.info(e); @@ -133,7 +135,7 @@ public class SvnChangelistListener implements ChangeListListener { final List paths = getPathsFromChanges(list.getChanges()); for (String path : paths) { try { - myClient.doAddToChangelist(new File[]{new File(path)}, SVNDepth.EMPTY, list.getName(), null); + myVcs.createChangelistClient().doAddToChangelist(new File[]{new File(path)}, SVNDepth.EMPTY, list.getName(), null); } catch (SVNException e) { LOG.info(e); @@ -156,7 +158,7 @@ public class SvnChangelistListener implements ChangeListListener { final List paths = getPathsFromChanges(changes); for (final String path : paths) { try { - myClient.doAddToChangelist(new File[]{new File(path)}, SVNDepth.EMPTY, toList.getName(), fromLists); + myVcs.createChangelistClient().doAddToChangelist(new File[]{new File(path)}, SVNDepth.EMPTY, toList.getName(), fromLists); } catch (SVNException e) { LOG.info(e); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRecursiveStatusWalker.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRecursiveStatusWalker.java index eef6ec71b071..c1337e505132 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRecursiveStatusWalker.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRecursiveStatusWalker.java @@ -67,36 +67,38 @@ public class SvnRecursiveStatusWalker { myHandler.checkIfCopyRootWasReported(); } catch (SVNException e) { - if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_DIRECTORY) { - final VirtualFile virtualFile = path.getVirtualFile(); - if (virtualFile != null) { - if (myPartner.isExcluded(virtualFile)) return; - // self is unversioned - myReceiver.processUnversioned(virtualFile); - - processRecursively(virtualFile, item.getDepth()); - } - } else { - throw e; - } + handleStatusException(item, path, e); } } else { - if (item.isIsInnerCopyRoot()) { - // this means that the status of parent directory had already been checked and is unversioned; - // to avoid SVN exception on status query to unversioned directory; and since we already know then that the file - // status is "unversioned" -> just register the unversioned file - if (path.getVirtualFile() != null) { - myReceiver.processUnversioned(path.getVirtualFile()); - } - } else { - // just file + try { final SVNStatus status = item.getClient().doStatus(ioFile, false, false); myReceiver.process(path, status); + } catch (SVNException e) { + handleStatusException(item, path, e); } } } } + private void handleStatusException(MyItem item, FilePath path, SVNException e) throws SVNException { + final SVNErrorCode errorCode = e.getErrorMessage().getErrorCode(); + if (SVNErrorCode.WC_NOT_DIRECTORY.equals(errorCode) || SVNErrorCode.WC_NOT_FILE.equals(errorCode)) { + final VirtualFile virtualFile = path.getVirtualFile(); + if (virtualFile != null) { + if (! myPartner.isExcluded(virtualFile)) { + // self is unversioned + myReceiver.processUnversioned(virtualFile); + + if (virtualFile.isDirectory()) { + processRecursively(virtualFile, item.getDepth()); + } + } + } + } else { + throw e; + } + } + private static class MyItem { private final Project myProject; private final FilePath myPath; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnVcs.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnVcs.java index 00c62c3f744f..2634f757e5d6 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnVcs.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnVcs.java @@ -239,7 +239,7 @@ public class SvnVcs extends AbstractVcs { myEntriesFileListener = new SvnEntriesFileListener(project); upgradeIfNeeded(bus); - myChangeListListener = new SvnChangelistListener(myProject, createChangelistClient()); + myChangeListListener = new SvnChangelistListener(myProject, this); myVcsListener = new VcsListener() { @Override diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/TreeConflictRefreshablePanel.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/TreeConflictRefreshablePanel.java index fec9c72b402b..5b8aafc9e2a4 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/TreeConflictRefreshablePanel.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/TreeConflictRefreshablePanel.java @@ -325,7 +325,7 @@ public class TreeConflictRefreshablePanel extends AbstractRefreshablePanel { additionalPath = myChange.getAfterRevision().getFile(); } } else { - if (myChange.getBeforeDescription() != null) { + if (myChange.getBeforeRevision() != null) { mainPath = myChange.getBeforeRevision().getFile(); } else { mainPath = myChange.getAfterRevision().getFile(); diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/DesignerToolWindowManager.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/DesignerToolWindowManager.java index 926e87fb7dc5..1a8bb56b79b5 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/DesignerToolWindowManager.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/DesignerToolWindowManager.java @@ -17,7 +17,6 @@ package com.intellij.designer; import com.intellij.designer.componentTree.ComponentTree; import com.intellij.designer.componentTree.ComponentTreeBuilder; -import com.intellij.designer.componentTree.TreeEditableArea; import com.intellij.designer.designSurface.DesignerEditorPanel; import com.intellij.designer.propertyTable.PropertyTablePanel; import com.intellij.openapi.actionSystem.AnAction; @@ -135,11 +134,6 @@ public final class DesignerToolWindowManager implements ProjectComponent { } } - @Nullable - public TreeEditableArea getTreeArea() { - return myTreeBuilder == null ? null : myTreeBuilder.getTreeArea(); - } - @Nullable private static DesignerEditorPanel getDesigner(FileEditor editor) { if (editor instanceof DesignerEditor) { diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/actions/CommonEditActionsProvider.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/actions/CommonEditActionsProvider.java index 7a6bf5ae69da..c81c9d5ffb4a 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/actions/CommonEditActionsProvider.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/actions/CommonEditActionsProvider.java @@ -53,8 +53,9 @@ public class CommonEditActionsProvider implements DeleteProvider, CopyProvider, myDesigner = designer; } - protected EditableArea getArea() { - return myDesigner.getActionsArea(); + protected EditableArea getArea(DataContext dataContext) { + EditableArea area = EditableArea.DATA_KEY.getData(dataContext); + return area == null ? myDesigner.getSurfaceArea() : area; } ////////////////////////////////////////////////////////////////////////////////////////// @@ -68,7 +69,7 @@ public class CommonEditActionsProvider implements DeleteProvider, CopyProvider, if (myDesigner.getInplaceEditingLayer().isEditing()) { return false; } - List selection = getArea().getSelection(); + List selection = getArea(dataContext).getSelection(); if (selection.isEmpty()) { return false; } @@ -81,11 +82,11 @@ public class CommonEditActionsProvider implements DeleteProvider, CopyProvider, } @Override - public void deleteElement(@NotNull DataContext dataContext) { + public void deleteElement(final @NotNull DataContext dataContext) { myDesigner.getToolProvider().execute(new ThrowableRunnable() { @Override public void run() throws Exception { - EditableArea area = getArea(); + EditableArea area = getArea(dataContext); List selection = area.getSelection(); if (selection.isEmpty()) { @@ -145,20 +146,20 @@ public class CommonEditActionsProvider implements DeleteProvider, CopyProvider, @Override public boolean isCopyEnabled(@NotNull DataContext dataContext) { - return !myDesigner.getInplaceEditingLayer().isEditing() && !getArea().getSelection().isEmpty(); + return !myDesigner.getInplaceEditingLayer().isEditing() && !getArea(dataContext).getSelection().isEmpty(); } @Override public void performCopy(@NotNull DataContext dataContext) { - doCopy(); + doCopy(dataContext); } - private boolean doCopy() { + private boolean doCopy(DataContext dataContext) { try { Element root = new Element("designer"); root.setAttribute("target", myDesigner.getPlatformTarget()); - List components = RadComponent.getPureSelection(getArea().getSelection()); + List components = RadComponent.getPureSelection(getArea(dataContext).getSelection()); for (RadComponent component : components) { component.copyTo(root); } @@ -243,7 +244,7 @@ public class CommonEditActionsProvider implements DeleteProvider, CopyProvider, @Override public void performCut(@NotNull DataContext dataContext) { - if (doCopy()) { + if (doCopy(dataContext)) { deleteElement(dataContext); } } diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/componentTree/ComponentTree.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/componentTree/ComponentTree.java index e39eb730ca18..633ed1da333f 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/componentTree/ComponentTree.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/componentTree/ComponentTree.java @@ -18,6 +18,7 @@ package com.intellij.designer.componentTree; import com.intellij.designer.actions.DesignerActionPanel; import com.intellij.designer.actions.StartInplaceEditing; import com.intellij.designer.designSurface.DesignerEditorPanel; +import com.intellij.designer.designSurface.EditableArea; import com.intellij.designer.designSurface.FeedbackTreeLayer; import com.intellij.designer.model.RadComponent; import com.intellij.openapi.actionSystem.DataProvider; @@ -40,6 +41,7 @@ public final class ComponentTree extends Tree implements DataProvider { private final StartInplaceEditing myInplaceEditingAction; private TreeComponentDecorator myDecorator; private DesignerActionPanel myActionPanel; + private EditableArea myArea; private RadComponent myMarkComponent; private int myMarkFeedback; @@ -75,9 +77,14 @@ public final class ComponentTree extends Tree implements DataProvider { myActionPanel = designer.getActionPanel(); } myMarkComponent = null; + myArea = null; myInplaceEditingAction.setDesignerPanel(designer); } + public void setArea(@Nullable EditableArea area) { + myArea = area; + } + public void mark(RadComponent component, int feedback) { myMarkComponent = component; myMarkFeedback = feedback; @@ -86,7 +93,13 @@ public final class ComponentTree extends Tree implements DataProvider { @Override public Object getData(@NonNls String dataId) { - return myActionPanel == null ? null : myActionPanel.getData(dataId); + if (EditableArea.DATA_KEY.is(dataId)) { + return myArea; + } + if (myActionPanel != null) { + return myActionPanel.getData(dataId); + } + return null; } @Nullable diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/componentTree/ComponentTreeBuilder.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/componentTree/ComponentTreeBuilder.java index e5fecc7c0cd3..e1e29059a39d 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/componentTree/ComponentTreeBuilder.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/componentTree/ComponentTreeBuilder.java @@ -49,6 +49,8 @@ public final class ComponentTreeBuilder extends AbstractTreeBuilder implements C myGlassLayer = new TreeGlassLayer(tree, designer.getToolProvider(), myTreeArea); myExpandStateHandler = new ExpandStateHandler(tree, designer, this); + tree.setArea(myTreeArea); + new TreeDropListener(tree, myTreeArea, designer.getToolProvider()); selectFromSurface(); diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/CaptionPanel.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/CaptionPanel.java index 19af11b3eb39..7eb831645f13 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/CaptionPanel.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/CaptionPanel.java @@ -150,7 +150,7 @@ public class CaptionPanel extends JLayeredPane implements DataProvider, DeletePr myActionsProvider = new CommonEditActionsProvider(designer) { @Override - protected EditableArea getArea() { + protected EditableArea getArea(DataContext dataContext) { return myArea; } }; diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/DesignerEditorPanel.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/DesignerEditorPanel.java index 2ee177594ddf..6f9520fbb573 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/DesignerEditorPanel.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/DesignerEditorPanel.java @@ -19,7 +19,6 @@ import com.intellij.designer.DesignerEditorState; import com.intellij.designer.DesignerToolWindowManager; import com.intellij.designer.actions.DesignerActionPanel; import com.intellij.designer.componentTree.TreeComponentDecorator; -import com.intellij.designer.componentTree.TreeEditableArea; import com.intellij.designer.designSurface.tools.*; import com.intellij.designer.model.FindComponentVisitor; import com.intellij.designer.model.RadComponent; @@ -29,10 +28,13 @@ import com.intellij.designer.propertyTable.Property; import com.intellij.diagnostic.LogMessageEx; import com.intellij.diagnostic.errordialog.Attachment; import com.intellij.ide.palette.impl.PaletteManager; -import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.actionSystem.ActionGroup; +import com.intellij.openapi.actionSystem.ActionPlaces; +import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; +import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.VerticalFlowLayout; @@ -106,6 +108,8 @@ public abstract class DesignerEditorPanel extends JPanel implements DataProvider protected RadComponent myRootComponent; + protected QuickFixManager myQuickFixManager; + private List myExpandedComponents; private Property mySelectionProperty; private int[][] myExpandedState; @@ -300,6 +304,8 @@ public abstract class DesignerEditorPanel extends JPanel implements DataProvider myHorizontalCaption.attachToScrollPane(myScrollPane); myVerticalCaption.attachToScrollPane(myScrollPane); + myQuickFixManager = new QuickFixManager(this, myGlassLayer, myScrollPane.getViewport()); + myActionPanel = new DesignerActionPanel(this, myGlassLayer); myDesignerCard = new JPanel(new FillLayout()); @@ -510,11 +516,6 @@ public abstract class DesignerEditorPanel extends JPanel implements DataProvider return mySurfaceArea; } - public EditableArea getActionsArea() { - TreeEditableArea treeArea = DesignerToolWindowManager.getInstance(getProject()).getTreeArea(); - return treeArea == null ? mySurfaceArea : treeArea; - } - public ToolProvider getToolProvider() { return myToolProvider; } @@ -713,6 +714,19 @@ public abstract class DesignerEditorPanel extends JPanel implements DataProvider public abstract TreeComponentDecorator getTreeDecorator(); + ////////////////////////////////////////////////////////////////////////////////////////// + // + // Inspection + // + ////////////////////////////////////////////////////////////////////////////////////////// + + public void loadInspections(ProgressIndicator progress) { + } + + public void updateInspections() { + myQuickFixManager.update(); + } + ////////////////////////////////////////////////////////////////////////////////////////// // // diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/EditableArea.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/EditableArea.java index 285dfec7b781..ebc32a71ad76 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/EditableArea.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/EditableArea.java @@ -18,6 +18,7 @@ package com.intellij.designer.designSurface; import com.intellij.designer.designSurface.tools.InputTool; import com.intellij.designer.model.RadComponent; import com.intellij.openapi.actionSystem.ActionGroup; +import com.intellij.openapi.actionSystem.DataKey; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -29,6 +30,8 @@ import java.util.List; * @author Alexander Lobas */ public interface EditableArea { + DataKey DATA_KEY = DataKey.create("EditableArea"); + ////////////////////////////////////////////////////////////////////////////////////////// // // Selection diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/GlassLayer.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/GlassLayer.java index 2d4719534750..f28b4c94f2c2 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/GlassLayer.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/GlassLayer.java @@ -17,7 +17,6 @@ package com.intellij.designer.designSurface; import com.intellij.designer.designSurface.tools.ToolProvider; import com.intellij.openapi.actionSystem.DataProvider; -import com.intellij.ui.popup.PopupOwner; import org.jetbrains.annotations.NonNls; import javax.swing.*; @@ -28,7 +27,7 @@ import java.awt.event.MouseEvent; /** * @author Alexander Lobas */ -public final class GlassLayer extends JComponent implements PopupOwner, DataProvider { +public final class GlassLayer extends JComponent implements DataProvider { private static final long EVENT_FLAGS = AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK; private final ToolProvider myToolProvider; @@ -74,13 +73,8 @@ public final class GlassLayer extends JComponent implements PopupOwner, DataProv myToolProvider.processMouseEvent(event, myArea); } - @Override - public Point getBestPopupPosition() { - return null; // TODO: Auto-generated method stub - } - @Override public Object getData(@NonNls String dataId) { - return null; // TODO: Auto-generated method stub + return EditableArea.DATA_KEY.is(dataId) ? myArea : null; } } \ No newline at end of file diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/InplaceEditingLayer.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/InplaceEditingLayer.java index 560619fce313..a0a8cbfe7b86 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/InplaceEditingLayer.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/InplaceEditingLayer.java @@ -15,6 +15,7 @@ */ package com.intellij.designer.designSurface; +import com.intellij.designer.DesignerBundle; import com.intellij.designer.designSurface.feedbacks.LineMarginBorder; import com.intellij.designer.model.RadComponent; import com.intellij.designer.propertyTable.InplaceContext; @@ -27,11 +28,13 @@ import com.intellij.openapi.actionSystem.CustomShortcutSet; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.util.Comparing; import com.intellij.openapi.wm.FocusWatcher; import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy; import com.intellij.openapi.wm.ex.LayoutFocusTraversalPolicyExt; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; +import com.intellij.util.ThrowableRunnable; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -87,6 +90,9 @@ public class InplaceEditingLayer extends JComponent { adjustInplaceComponentSize(); } }; + + private RadComponent myRadComponent; + private List myProperties; private List myEditors; private final DesignerEditorPanel myDesigner; @@ -104,13 +110,15 @@ public class InplaceEditingLayer extends JComponent { return; } - RadComponent radComponent = selection.get(0); - List inplaceProperties = radComponent.getInplaceProperties(); - if (inplaceProperties.isEmpty()) { + myRadComponent = selection.get(0); + myProperties = myRadComponent.getInplaceProperties(); + if (myProperties.isEmpty()) { + myRadComponent = null; + myProperties = null; return; } - myInplaceComponent = new JPanel(new GridLayoutManager(inplaceProperties.size(), 2)); + myInplaceComponent = new JPanel(new GridLayoutManager(myProperties.size(), 2)); myInplaceComponent.setBorder(new LineMarginBorder(5, 5, 5, 5)); new AnAction() { @Override @@ -119,8 +127,6 @@ public class InplaceEditingLayer extends JComponent { } }.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0)), myInplaceComponent); - int row = 0; - myEditors = new ArrayList(); JComponent componentToFocus = null; @@ -130,7 +136,8 @@ public class InplaceEditingLayer extends JComponent { inplaceContext = new InplaceContext(); } - for (Property property : inplaceProperties) { + int row = 0; + for (Property property : myProperties) { JLabel label = new JLabel(property.getName() + ":"); if (font == null) { font = label.getFont().deriveFont(Font.BOLD); @@ -144,11 +151,12 @@ public class InplaceEditingLayer extends JComponent { PropertyEditor editor = property.getEditor(); myEditors.add(editor); - JComponent component = editor.getComponent(radComponent.getRoot(), radComponent, property.getValue(radComponent), inplaceContext); + JComponent component = + editor.getComponent(myRadComponent.getRoot(), myRadComponent, property.getValue(myRadComponent), inplaceContext); myInplaceComponent.add(component, - new GridConstraints(row++, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, 0, 0, - null, null, null)); + new GridConstraints(row++, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, + GridConstraints.SIZEPOLICY_CAN_GROW, 0, null, null, null)); if (componentToFocus == null) { componentToFocus = editor.getPreferredFocusedComponent(); @@ -159,10 +167,10 @@ public class InplaceEditingLayer extends JComponent { editor.addPropertyEditorListener(myEditorListener); } - Rectangle bounds = radComponent.getBounds(this); + Rectangle bounds = myRadComponent.getBounds(this); Dimension size = myInplaceComponent.getPreferredSize(); - myPreferredWidth = size.width; - myInplaceComponent.setBounds(bounds.x, bounds.y, size.width, size.height); + myPreferredWidth = Math.max(size.width, bounds.width); + myInplaceComponent.setBounds(bounds.x, bounds.y, myPreferredWidth, size.height); add(myInplaceComponent); if (componentToFocus == null) { @@ -191,7 +199,22 @@ public class InplaceEditingLayer extends JComponent { if (myInplaceComponent != null) { if (commit) { - // TODO: Auto-generated method stub + myDesigner.getToolProvider().execute(new ThrowableRunnable() { + @Override + public void run() throws Exception { + int size = myProperties.size(); + + for (int i = 0; i < size; i++) { + Property property = myProperties.get(i); + Object oldValue = property.getValue(myRadComponent); + Object newValue = myEditors.get(i).getValue(); + + if (!Comparing.equal(oldValue, newValue)) { + property.setValue(myRadComponent, newValue); + } + } + } + }, DesignerBundle.message("command.set.property.value"), true); } for (PropertyEditor editor : myEditors) { @@ -203,6 +226,8 @@ public class InplaceEditingLayer extends JComponent { myInplaceComponent = null; } + myRadComponent = null; + myProperties = null; myEditors = null; myDesigner.getPreferredFocusedComponent().requestFocusInWindow(); @@ -214,11 +239,9 @@ public class InplaceEditingLayer extends JComponent { private void adjustInplaceComponentSize() { myInplaceComponent.revalidate(); Dimension size = myInplaceComponent.getPreferredSize(); - int width = Math.max(size.width, myPreferredWidth); - width = Math.min(width, getWidth() - myInplaceComponent.getX()); - myInplaceComponent.setSize(width, myInplaceComponent.getHeight()); + myInplaceComponent.setSize(Math.max(size.width, myPreferredWidth), myInplaceComponent.getHeight()); myInplaceComponent.revalidate(); - System.out.println("size: " + width); + repaint(); } private void removeInplaceComponent() { diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/QuickFixManager.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/QuickFixManager.java new file mode 100644 index 000000000000..1ffc96c79dc6 --- /dev/null +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/QuickFixManager.java @@ -0,0 +1,64 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.designer.designSurface; + +import com.intellij.designer.inspection.AbstractQuickFixManager; +import com.intellij.designer.inspection.ErrorInfo; +import com.intellij.designer.model.RadComponent; +import org.jetbrains.annotations.NotNull; + +import javax.swing.*; +import java.awt.*; +import java.util.List; + +/** + * @author Alexander Lobas + */ +public class QuickFixManager extends AbstractQuickFixManager implements ComponentSelectionListener { + public QuickFixManager(DesignerEditorPanel designer, JComponent component, JViewport viewPort) { + super(designer, component, viewPort); + designer.getSurfaceArea().addSelectionListener(this); + } + + @Override + public void selectionChanged(EditableArea area) { + hideHint(); + updateHintVisibility(); + } + + @NotNull + @Override + protected ErrorInfo[] getErrorInfos() { + return new ErrorInfo[0]; // TODO: Auto-generated method stub + } + + @Override + protected Rectangle getErrorBounds() { + List selection = myDesigner.getSurfaceArea().getSelection(); + if (selection.size() == 1) { + return selection.get(0).getBounds(myComponent); + } + + return null; + } + + @Override + protected Rectangle getHintClipRect() { + Rectangle clipRect = super.getHintClipRect(); + clipRect.grow(4, 4); + return clipRect; + } +} \ No newline at end of file diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/tools/SelectionTool.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/tools/SelectionTool.java index 7efcfb6c1f7c..077c881ebca9 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/tools/SelectionTool.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/designSurface/tools/SelectionTool.java @@ -89,7 +89,7 @@ public class SelectionTool extends InputTool { @Override protected void handleDoubleClick(int button) { - if (button == MouseEvent.BUTTON1 && myToolProvider != null) { + if (button == MouseEvent.BUTTON1 && myToolProvider != null && !myArea.isTree()) { myToolProvider.startInplaceEditing(null); } } @@ -199,7 +199,7 @@ public class SelectionTool extends InputTool { if (myTracker != null) { myTracker.keyTyped(event, area); } - else if (myToolProvider != null && + else if (myToolProvider != null && !area.isTree() && Character.isLetterOrDigit(event.getKeyChar()) && (event.getModifiers() & (InputEvent.ALT_MASK | InputEvent.CTRL_MASK)) == 0) { myToolProvider.startInplaceEditing(new InplaceContext(event.getKeyChar())); diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/AbstractQuickFixManager.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/AbstractQuickFixManager.java new file mode 100644 index 000000000000..7e51e86ff5c1 --- /dev/null +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/AbstractQuickFixManager.java @@ -0,0 +1,282 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.designer.inspection; + +import com.intellij.designer.DesignerBundle; +import com.intellij.designer.designSurface.DesignerEditorPanel; +import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.keymap.KeymapUtil; +import com.intellij.openapi.util.IconLoader; +import com.intellij.openapi.wm.impl.VisibilityWatcher; +import com.intellij.ui.HintHint; +import com.intellij.ui.LightweightHint; +import com.intellij.ui.RowIcon; +import com.intellij.util.Alarm; +import com.intellij.util.IJSwingUtilities; +import com.intellij.util.ui.EmptyIcon; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import javax.swing.border.Border; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import java.awt.*; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +/** + * @author Alexander Lobas + * @author Anton Katilin + * @author Vladimir Kondratyev + */ +public abstract class AbstractQuickFixManager { + protected DesignerEditorPanel myDesigner; + protected final JComponent myComponent; + private final JViewport myViewPort; + private final Alarm myAlarm = new Alarm(); + private final Runnable myShowHintRequest; + private LightweightHint myHint; + private Rectangle myLastHintBounds; + + public AbstractQuickFixManager(DesignerEditorPanel designer, JComponent component, JViewport viewPort) { + myDesigner = designer; + myComponent = component; + myViewPort = viewPort; + + myShowHintRequest = new Runnable() { + @Override + public void run() { + showHint(); + } + }; + + new VisibilityWatcher() { + @Override + public void visibilityChanged() { + if (myComponent.isShowing()) { + updateHintVisibility(); + } + else { + hideHint(); + } + } + }.install(component); + + component.addFocusListener(new FocusListener() { + @Override + public void focusGained(FocusEvent e) { + if (!e.isTemporary()) { + updateHintVisibility(); + } + } + + @Override + public void focusLost(FocusEvent e) { + if (!(e.isTemporary())) { + hideHint(); + } + } + }); + + AnAction showHintAction = new AnAction() { + @Override + public void actionPerformed(AnActionEvent e) { + if (myDesigner != null) { + showHint(); + showPopup(); + } + } + + @Override + public void update(AnActionEvent e) { + e.getPresentation().setEnabled(e.getData(PlatformDataKeys.EDITOR) == null); + } + }; + showHintAction.registerCustomShortcutSet( + ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS).getShortcutSet(), component); + + viewPort.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + updateHintPosition(); + } + }); + } + + public void setDesigner(DesignerEditorPanel designer) { + myDesigner = designer; + } + + public void update() { + if (!myComponent.isShowing() || !IJSwingUtilities.hasFocus(myComponent)) { + hideHint(); + } + else if (myHint == null || !myHint.isVisible()) { + updateHintVisibility(); + } + else { + ErrorInfo[] errorInfos = getErrorInfos(); + Rectangle bounds = getErrorBounds(); + if (!haveFixes(errorInfos) || bounds == null || !bounds.equals(myLastHintBounds)) { + hideHint(); + updateHintVisibility(); + } + } + } + + private static boolean haveFixes(ErrorInfo[] errorInfos) { + // XXX + return true; + } + + private void showHint() { + if (!myComponent.isShowing() || !IJSwingUtilities.hasFocus(myComponent)) { + hideHint(); + return; + } + + // 1. Hide previous hint (if any) + hideHint(); + + // 2. Found error (if any) + ErrorInfo[] errorInfos = getErrorInfos(); + if (!haveFixes(errorInfos)) { + hideHint(); + return; + } + + // 3. Determine position where this hint should be shown + Rectangle bounds = getErrorBounds(); + if (bounds == null) { + return; + } + + // 4. Show light bulb to fix this error + myHint = new LightweightHint(new InspectionHint()); + myLastHintBounds = bounds; + myHint.show(myComponent, bounds.x - ICON.getIconWidth() - 4, bounds.y, myComponent, new HintHint(myComponent, bounds.getLocation())); + } + + private void showPopup() { + // TODO: Auto-generated method stub + } + + protected void hideHint() { + myAlarm.cancelAllRequests(); + if (myHint != null && myHint.isVisible()) { + myHint.hide(); + myHint = null; + myComponent.paintImmediately(myComponent.getVisibleRect()); + } + } + + protected void updateHintVisibility() { + myAlarm.cancelAllRequests(); + myAlarm.addRequest(myShowHintRequest, 500); + } + + private void updateHintPosition() { + if (myHint != null && myHint.isVisible()) { + Rectangle rc = getErrorBounds(); + if (rc != null) { + myLastHintBounds = rc; + Rectangle hintRect = new Rectangle(rc.x - ICON.getIconWidth() - 4, rc.y, ICON.getIconWidth() + 4, ICON.getIconHeight() + 4); + if (getHintClipRect().contains(hintRect)) { + myHint.updateLocation(hintRect.x, hintRect.y); + } + else { + myHint.hide(); + } + } + } + } + + protected Rectangle getHintClipRect() { + return myViewPort.getViewRect(); + } + + /** + * @return error info for the current {@link #myComponent} state. + */ + @NotNull + protected abstract ErrorInfo[] getErrorInfos(); + + /** + * @return rectangle (in {@link #myComponent} coordinates) that represents + * area that contains errors. This methods is invoked only if {@link #getErrorInfos()} + * returned non empty list of error infos. null means that + * error bounds are not defined. + */ + @Nullable + protected abstract Rectangle getErrorBounds(); + + private static final Border INACTIVE_BORDER = BorderFactory.createEmptyBorder(4, 4, 4, 4); + private static final Border ACTIVE_BORDER = + BorderFactory + .createCompoundBorder(BorderFactory.createLineBorder(Color.orange, 2), BorderFactory.createEmptyBorder(2, 2, 2, 2)); + + private static final Icon ARROW_ICON = IconLoader.getIcon("/general/arrowDown.png"); + private static final Icon INACTIVE_ARROW_ICON = new EmptyIcon(ARROW_ICON.getIconWidth(), ARROW_ICON.getIconHeight()); + private static final Icon ICON = IconLoader.findIcon("/actions/intentionBulb.png"); + + private class InspectionHint extends JLabel { + private final RowIcon myInactiveIcon; + private final RowIcon myActiveIcon; + + private InspectionHint() { + setOpaque(false); + setBorder(INACTIVE_BORDER); + + myActiveIcon = new RowIcon(2); + myActiveIcon.setIcon(ICON, 0); + myActiveIcon.setIcon(ARROW_ICON, 1); + + myInactiveIcon = new RowIcon(2); + myInactiveIcon.setIcon(ICON, 0); + myInactiveIcon.setIcon(INACTIVE_ARROW_ICON, 1); + + setIcon(myInactiveIcon); + + String acceleratorsText = KeymapUtil.getFirstKeyboardShortcutText( + ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS)); + if (acceleratorsText.length() > 0) { + setToolTipText(DesignerBundle.message("tooltip.press.accelerator", acceleratorsText)); + } + + addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + setIcon(myActiveIcon); + setBorder(ACTIVE_BORDER); + } + + @Override + public void mouseExited(MouseEvent e) { + setIcon(myInactiveIcon); + setBorder(INACTIVE_BORDER); + } + + @Override + public void mouseClicked(MouseEvent e) { + showPopup(); + } + }); + } + } +} \ No newline at end of file diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/DesignerBackgroundEditorHighlighter.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/DesignerBackgroundEditorHighlighter.java new file mode 100644 index 000000000000..3c74b71eaa22 --- /dev/null +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/DesignerBackgroundEditorHighlighter.java @@ -0,0 +1,44 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.designer.inspection; + +import com.intellij.codeHighlighting.BackgroundEditorHighlighter; +import com.intellij.codeHighlighting.HighlightingPass; +import com.intellij.designer.designSurface.DesignerEditorPanel; +import org.jetbrains.annotations.NotNull; + +/** + * @author Alexander Lobas + */ +public final class DesignerBackgroundEditorHighlighter implements BackgroundEditorHighlighter { + private final HighlightingPass[] myHighlightingPasses; + + public DesignerBackgroundEditorHighlighter(DesignerEditorPanel designer) { + myHighlightingPasses = new HighlightingPass[]{new DesignerHighlightingPass(designer)}; + } + + @NotNull + @Override + public HighlightingPass[] createPassesForEditor() { + return myHighlightingPasses; + } + + @NotNull + @Override + public HighlightingPass[] createPassesForVisibleArea() { + return HighlightingPass.EMPTY_ARRAY; + } +} \ No newline at end of file diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/DesignerHighlightingPass.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/DesignerHighlightingPass.java new file mode 100644 index 000000000000..dc6d6a554dbf --- /dev/null +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/DesignerHighlightingPass.java @@ -0,0 +1,41 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.designer.inspection; + +import com.intellij.codeHighlighting.HighlightingPass; +import com.intellij.designer.designSurface.DesignerEditorPanel; +import com.intellij.openapi.progress.ProgressIndicator; + +/** + * @author Alexander Lobas + */ +public final class DesignerHighlightingPass implements HighlightingPass { + private final DesignerEditorPanel myDesigner; + + public DesignerHighlightingPass(DesignerEditorPanel designer) { + myDesigner = designer; + } + + @Override + public void collectInformation(ProgressIndicator progress) { + myDesigner.loadInspections(progress); + } + + @Override + public void applyInformationToEditor() { + myDesigner.updateInspections(); + } +} \ No newline at end of file diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/ErrorAnalyzerManager.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/ErrorAnalyzerManager.java new file mode 100644 index 000000000000..1fe70c2fb881 --- /dev/null +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/ErrorAnalyzerManager.java @@ -0,0 +1,22 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.designer.inspection; + +/** + * @author Alexander Lobas + */ +public final class ErrorAnalyzerManager { +} \ No newline at end of file diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/ErrorInfo.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/ErrorInfo.java new file mode 100644 index 000000000000..43c3a4fa4a2e --- /dev/null +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/inspection/ErrorInfo.java @@ -0,0 +1,22 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.designer.inspection; + +/** + * @author Alexander Lobas + */ +public class ErrorInfo { +} \ No newline at end of file diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/model/RadComponent.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/model/RadComponent.java index c43400d71452..ffd7f5ad3064 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/model/RadComponent.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/model/RadComponent.java @@ -111,6 +111,8 @@ public abstract class RadComponent { if (myLayout != null) { myLayout.removeComponentFromContainer(component); } + + component.setParent(null); } public void removeFromParent() { diff --git a/plugins/ui-designer/ui-designer-new/src/messages/DesignerBundle.properties b/plugins/ui-designer/ui-designer-new/src/messages/DesignerBundle.properties index aeb0e5ad1812..87decad7bb4b 100644 --- a/plugins/ui-designer/ui-designer-new/src/messages/DesignerBundle.properties +++ b/plugins/ui-designer/ui-designer-new/src/messages/DesignerBundle.properties @@ -15,4 +15,6 @@ designer.properties.column2=Value designer.properties.getting.error=Error getting value: {0} designer.properties.setting.error=Error setting value: {0} designer.properties.no_message.error=No message -designer.properties.invalid_input=Invalid Input \ No newline at end of file +designer.properties.invalid_input=Invalid Input + +tooltip.press.accelerator=Click or press {0} \ No newline at end of file diff --git a/resources-en/src/messages/QuickFixBundle.properties b/resources-en/src/messages/QuickFixBundle.properties index bd107e9cb0db..a5cda760fc2f 100644 --- a/resources-en/src/messages/QuickFixBundle.properties +++ b/resources-en/src/messages/QuickFixBundle.properties @@ -266,4 +266,6 @@ initialize.final.field.in.constructor.name=Initialize in constructor initialize.final.field.in.constructor.choose.dialog.title=Choose constructors to add initialization to remove.redundant.arguments.text=Remove redundant arguments to call ''{0}'' -remove.redundant.arguments.family=Remove redundant arguments \ No newline at end of file +remove.redundant.arguments.family=Remove redundant arguments + +replace.with.list.access.text=Replace with list access \ No newline at end of file diff --git a/xml/dom-impl/src/com/intellij/util/xml/structure/DomStructureTreeElement.java b/xml/dom-impl/src/com/intellij/util/xml/structure/DomStructureTreeElement.java index 6bf21d939aeb..dab3f07d68f9 100644 --- a/xml/dom-impl/src/com/intellij/util/xml/structure/DomStructureTreeElement.java +++ b/xml/dom-impl/src/com/intellij/util/xml/structure/DomStructureTreeElement.java @@ -52,7 +52,7 @@ public class DomStructureTreeElement implements StructureViewTreeElement, ItemPr } public Object getValue() { - return !myElement.isValid() ? null : myElement.getXmlElement(); + return myElement.getXmlElement(); } public ItemPresentation getPresentation() {