# ---------------------------------------------------------------------
if [ -z "$IDEA_JDK" ]; then
IDEA_JDK=$JDK_HOME
+ if [ -z "$IDEA_JDK" -a -e "$JAVA_HOME/lib/tools.jar" ]; then
+ IDEA_JDK=$JAVA_HOME
+ fi
+ if [ -z "$IDEA_JDK" ]; then
+ # Try to get the jdk path from java binary path
+ JAVA_BIN_PATH=`which java`
+ if [ -n "$JAVA_BIN_PATH" ]; then
+ JAVA_LOCATION=`readlink -f $JAVA_BIN_PATH | xargs dirname | xargs dirname | xargs dirname`
+ if [ -x "$JAVA_LOCATION/bin/java" -a -e "$JAVA_LOCATION/lib/tools.jar" ]; then
+ IDEA_JDK=$JAVA_LOCATION
+ fi
+ fi
+ fi
if [ -z "$IDEA_JDK" ]; then
echo ERROR: cannot start IntelliJ IDEA.
echo No JDK found to run IDEA. Please validate either IDEA_JDK or JDK_HOME points to valid JDK installation
package com.intellij.compiler.actions;
import com.intellij.history.LocalHistory;
-import com.intellij.history.LocalHistoryConfiguration;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
protected void doAction(DataContext dataContext, final Project project) {
CompilerManager.getInstance(project).rebuild(new CompileStatusNotification() {
public void finished(boolean aborted, int errors, int warnings, final CompileContext compileContext) {
- if (!aborted && LocalHistoryConfiguration.getInstance().ADD_LABEL_ON_PROJECT_COMPILATION) {
- String text = getTemplatePresentation().getText();
- if (!project.isDisposed()) {
- LocalHistory.putSystemLabel(project, errors == 0
- ? CompilerBundle.message("rebuild.lvcs.label.no.errors", text)
- : CompilerBundle.message("rebuild.lvcs.label.with.errors", text));
- }
- }
+ if (aborted) return;
+
+ String text = getTemplatePresentation().getText();
+ LocalHistory.getInstance().putSystemLabel(project, errors == 0
+ ? CompilerBundle.message("rebuild.lvcs.label.no.errors", text)
+ : CompilerBundle.message("rebuild.lvcs.label.with.errors", text));
}
});
}
if (file.getFileSystem() instanceof LocalFileSystem) {
if (file.isDirectory()) {
if (dbOnly) {
- for (VirtualFile child : ((NewVirtualFile)file).getInDbChildren()) {
- if (NullVirtualFile.INSTANCE != child) {
- processRecursively(child, true, processor);
- }
+ for (VirtualFile child : ((NewVirtualFile)file).iterInDbChildren()) {
+ processRecursively(child, true, processor);
}
}
else {
import com.intellij.execution.process.ProcessListener;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.execution.runners.ProgramRunner;
-import com.intellij.execution.runners.ProgramRunnerUtil;
+import com.intellij.execution.runners.ExecutionUtil;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
// this problem to the user
SwingUtilities.invokeLater(new Runnable() {
public void run() {
- ProgramRunnerUtil.handleExecutionError(myProject, state.getRunnerSettings().getRunProfile(), e);
+ ExecutionUtil.handleExecutionError(myProject, state.getRunnerSettings().getRunProfile(), e);
}
});
}
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.JavaPatchableProgramRunner;
import com.intellij.execution.ui.RunContentDescriptor;
-import com.intellij.history.LocalHistory;
-import com.intellij.history.LocalHistoryConfiguration;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
protected RunContentDescriptor doExecute(final Project project, final Executor executor, final RunProfileState state, final RunContentDescriptor contentToReuse,
final ExecutionEnvironment env) throws ExecutionException {
FileDocumentManager.getInstance().saveAllDocuments();
+ return createContentDescriptor(project, executor, state, contentToReuse, env);
+ }
- if (LocalHistoryConfiguration.getInstance().ADD_LABEL_ON_RUNNING) {
- final String name = env.getRunProfile().getName();
- final String label = state instanceof RemoteState
- ? DebuggerBundle.message("debugger.runner.vcs.label.remote.debug", name)
- : DebuggerBundle.message("debugger.runner.vcs.label.debugging", name);
- LocalHistory.putSystemLabel(project, label);
- }
+ @Override
+ protected String getLocalHistoryLabel(RunProfile profile, RunProfileState state) {
+ final String name = profile.getName();
+ return state instanceof RemoteState
+ ? DebuggerBundle.message("debugger.runner.vcs.label.remote.debug", name)
+ : DebuggerBundle.message("debugger.runner.vcs.label.debugging", name);
- return createContentDescriptor(project, executor, state, contentToReuse, env);
}
@Nullable
}
public String suggestedName() {
- return ExecutionUtil.shortenName(JavaExecutionUtil.getShortClassName(MAIN_CLASS_NAME), 0);
+ return ProgramRunnerUtil.shortenName(JavaExecutionUtil.getShortClassName(MAIN_CLASS_NAME), 0);
}
public void setMainClassName(final String qualifiedName) {
}
public String suggestedName() {
- return ExecutionUtil.shortenName(JavaExecutionUtil.getShortClassName(MAIN_CLASS_NAME), 6) + ".main()";
+ return ProgramRunnerUtil.shortenName(JavaExecutionUtil.getShortClassName(MAIN_CLASS_NAME), 6) + ".main()";
}
public void setMainClassName(final String qualifiedName) {
final FrameworkSupportNode frameworkSupportNode = (FrameworkSupportNode)node;
frameworkSupportNode.setConfigurableComponentEnabled(node.isChecked());
updateOptionsPanel();
+ frameworkSupportNode.getConfigurable().onFrameworkSelectionChanged(node.isChecked());
myModel.onFrameworkSelectionChanged(frameworkSupportNode);
}
};
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Comparing;
-import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
super(project, MESSAGE, ProjectBundle.message("external.annotation.prompt"), Messages.getQuestionIcon());
myProject = project;
init();
- Disposer.register(myProject, myDisposable);
}
protected String getOkActionName() {
public void handleInsert(InsertionContext context, LookupElementDecorator<LookupItem> item) {
@SuppressWarnings({"unchecked"}) final LookupItem<PsiClass> delegate = item.getDelegate();
- delegate.handleInsert(context);
insertParentheses(context, delegate, delegate.getObject());
+ DefaultInsertHandler.addImportForItem(context.getFile(), context.getStartOffset(), delegate);
+
final PsiElement position = SmartCompletionDecorator.getPosition(context, delegate);
final PsiExpression enclosing = PsiTreeUtil.getContextOfType(position, PsiExpression.class, true);
}
public static void insertParentheses(InsertionContext context, LookupItem delegate, final PsiClass psiClass) {
- PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(context.getEditor().getDocument());
-
final PsiElement place = context.getFile().findElementAt(context.getStartOffset());
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(context.getProject()).getResolveHelper();
assert place != null;
final boolean needLeftParenth = isToInsertParenth();
final boolean hasParams = needLeftParenth && hasParams();
- if (CompletionUtil.isOverwrite(item, completionChar))
+ if (CompletionUtil.isOverwrite(item, completionChar)) {
removeEndOfIdentifier(needLeftParenth && hasParams);
- else if(myContext.getOffsetMap().getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET) != myContext.getSelectionEndOffset())
+ }
+ else if(myContext.getOffsetMap().getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET) != myContext.getSelectionEndOffset()) {
JavaCompletionUtil.resetParensInfo(context.getOffsetMap());
+ }
handleParenses(hasParams, needLeftParenth, tailType);
handleBrackets();
}
}
- private boolean isToInsertParenth(){
+ protected boolean isToInsertParenth(){
return insertingAnnotationWithParameters();
}
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PatternCondition;
-import static com.intellij.patterns.PsiJavaPatterns.*;
import com.intellij.patterns.PsiNameValuePairPattern;
import com.intellij.psi.*;
import com.intellij.psi.filters.*;
import java.util.LinkedHashSet;
import java.util.Set;
+import static com.intellij.patterns.PsiJavaPatterns.*;
+
/**
* @author peter
*/
@Nullable
private static ElementFilter getReferenceFilter(PsiElement position) {
// Completion after extends in interface, type parameter and implements in class
- final PsiClass containingClass = PsiTreeUtil.getParentOfType(position, PsiClass.class, false, PsiCodeBlock.class, PsiMethod.class, PsiExpressionList.class);
+ final PsiClass containingClass = PsiTreeUtil.getParentOfType(position, PsiClass.class, false, PsiCodeBlock.class, PsiMethod.class, PsiExpressionList.class, PsiVariable.class);
if (containingClass != null && psiElement().afterLeaf(PsiKeyword.EXTENDS, PsiKeyword.IMPLEMENTS, ",", "&").accepts(position)) {
return new AndFilter(ElementClassFilter.CLASS, new NotFilter(new AssignableFromContextFilter()));
}
new ParentElementFilter(new ClassFilter(PsiTryStatement.class)))
)));
public static final PsiJavaElementPattern.Capture<PsiElement> INSIDE_PARAMETER_LIST =
- PsiJavaPatterns.psiElement().withSuperParent(
- 2,
+ PsiJavaPatterns.psiElement().withParent(
psiElement(PsiJavaCodeReferenceElement.class).withParent(
psiElement(PsiTypeElement.class).withParent(PsiParameterList.class)));
public static final InsertHandler<JavaPsiClassReferenceElement> JAVA_CLASS_INSERT_HANDLER = new InsertHandler<JavaPsiClassReferenceElement>() {
public void handleInsert(final InsertionContext context, final JavaPsiClassReferenceElement item) {
if (completingRawConstructor(context, item)) {
- DefaultInsertHandler.NO_TAIL_HANDLER.handleInsert(context, item);
ConstructorInsertHandler.insertParentheses(context, item, item.getObject());
+ DefaultInsertHandler.addImportForItem(context.getFile(), context.getStartOffset(), item);
} else {
new DefaultInsertHandler().handleInsert(context, item);
}
JavaCompletionUtil.setShowFQN((LookupItem)item);
} else {
}
- ((LookupItem) item).setInsertHandler(DefaultInsertHandler.NO_TAIL_HANDLER);
result.addElement(decorate(LookupElementDecorator.withInsertHandler((LookupItem)item, ConstructorInsertHandler.INSTANCE), infos));
}
}
item.setAttribute(LookupItem.INDICATE_ANONYMOUS, "");
}
- item.setInsertHandler(DefaultInsertHandler.NO_TAIL_HANDLER);
result.addElement(decorate(type instanceof PsiClassType ? LookupElementDecorator.withInsertHandler(item, ConstructorInsertHandler.INSTANCE) : item, infos));
}
PsiElement element = file.findElementAt(context.getStartOffset());
if (element instanceof PsiIdentifier) {
element = element.getParent();
- while (element instanceof PsiJavaCodeReferenceElement || element instanceof PsiMethodCallExpression ||
+ while (element instanceof PsiJavaCodeReferenceElement || element instanceof PsiCall ||
element instanceof PsiThisExpression || element instanceof PsiSuperExpression ||
element instanceof PsiTypeElement ||
element instanceof PsiClassObjectAccessExpression) {
int newEnd = element.getTextRange().getEndOffset();
if (element instanceof PsiMethodCallExpression) {
- newEnd = ((PsiMethodCallExpression)element).getMethodExpression().getElement().getTextRange().getEndOffset();
+ newEnd = ((PsiMethodCallExpression)element).getMethodExpression().getTextRange().getEndOffset();
+ }
+ else if (element instanceof PsiNewExpression) {
+ final PsiJavaCodeReferenceElement classReference = ((PsiNewExpression)element).getClassReference();
+ if (classReference != null) {
+ newEnd = classReference.getTextRange().getEndOffset();
+ }
}
context.getOffsetMap().addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET, newEnd);
element = element.getParent();
"}";
private static final String INDENT_AND_BRACES_SAMPLE = "public class Foo {\n" +
+ " public Foo foo;\n" +
" public int[] X = new int[]{1, 3, 5 7, 9, 11};\n" +
"\n" +
" public void foo(boolean a, int x, int y, int z) {\n" +
" while (x < 10000);\n" +
" while (x < 50000) x++;\n" +
" for (int i = 0; i < 5; i++) System.out.println(i);\n" +
+ " foo.fooBar().fooBar()\n" +
+ " .fooBar().foo.fooBar().fooBar()\n" +
+ " .fooBar();\n" +
+ " }\n" +
+ "\n" +
+ " public Foo fooBar() {\n" +
+ " return this;\n" +
" }\n" +
"\n" +
" private class InnerClass implements I1, I2 {\n" +
myIsAfterClassKeyword = true;
}
if (childType == JavaElementType.METHOD_CALL_EXPRESSION) {
- result.add(createMethodCallExpressiobBlock(child,
+ result.add(createMethodCallExpressionBlock(child,
arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment)));
}
return role == ChildRole.OPERATION_SIGN || role == ChildRole.COLON;
}
- private Block createMethodCallExpressiobBlock(final ASTNode node, final Wrap blockWrap, final Alignment alignment) {
+ private Block createMethodCallExpressionBlock(final ASTNode node, final Wrap blockWrap, final Alignment alignment) {
final ArrayList<ASTNode> nodes = new ArrayList<ASTNode>();
final ArrayList<Block> subBlocks = new ArrayList<Block>();
collectNodes(nodes, node);
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.METHOD_CALL_CHAIN_WRAP), false);
+ // We use this alignment object to align chained method calls to the first method invocation place if necessary (see IDEA-30369)
+ Alignment chainedCallsAlignment = createAlignment(mySettings.ALIGN_MULTILINE_CHAINED_METHODS, null);
+
+ // We want to align chained method calls only if method target is explicitly specified, i.e. we don't want to align methods
+ // chain like 'recursive().recursive().recursive()' but want to align calls like 'foo.recursive().recursive().recursive()'
+ boolean callPointDefined = false;
+
while (!nodes.isEmpty()) {
ArrayList<ASTNode> subNodes = readToNextDot(nodes);
- subBlocks.add(createSynthBlock(subNodes, wrap));
+ Alignment alignmentToUseForSubBlock = null;
+
+ // Just create a no-aligned sub-block if we don't need to bother with it's alignment (either due to end-user
+ // setup or sub-block state).
+ if (chainedCallsAlignment == null || subNodes.isEmpty()) {
+ subBlocks.add(createSynthBlock(subNodes, wrap, alignmentToUseForSubBlock));
+ continue;
+ }
+
+ IElementType lastNodeType = subNodes.get(subNodes.size() - 1).getElementType();
+ boolean currentSubBlockIsMethodCall = lastNodeType == JavaElementType.EXPRESSION_LIST;
+
+ // Update information about chained method alignment point if necessary. I.e. we want to align only continuous method calls
+ // like 'foo.bar().bar().bar()' but not 'foo.bar().foo.bar()'
+ if (callPointDefined && !currentSubBlockIsMethodCall) {
+ chainedCallsAlignment = createAlignment(mySettings.ALIGN_MULTILINE_CHAINED_METHODS, null);
+ }
+ callPointDefined |= !currentSubBlockIsMethodCall;
+
+ // We want to align method call only if call target is defined for the first chained method and current block is a method call.
+ if (callPointDefined && currentSubBlockIsMethodCall) {
+ alignmentToUseForSubBlock = chainedCallsAlignment;
+ }
+ subBlocks.add(createSynthBlock(subNodes, wrap, alignmentToUseForSubBlock));
}
return new SyntheticCodeBlock(subBlocks, alignment, mySettings, Indent.getContinuationWithoutFirstIndent(),
blockWrap);
}
- private Block createSynthBlock(final ArrayList<ASTNode> subNodes, final Wrap wrap) {
+ private Block createSynthBlock(final ArrayList<ASTNode> subNodes, final Wrap wrap, final Alignment alignment) {
final ArrayList<Block> subBlocks = new ArrayList<Block>();
final ASTNode firstNode = subNodes.get(0);
if (firstNode.getElementType() == JavaTokenType.DOT) {
null));
subNodes.remove(0);
if (!subNodes.isEmpty()) {
- subBlocks.add(createSynthBlock(subNodes, wrap));
+ subBlocks.add(createSynthBlock(subNodes, wrap, null));
}
- return new SyntheticCodeBlock(subBlocks, null, mySettings, Indent.getContinuationIndent(), wrap);
+ return new SyntheticCodeBlock(subBlocks, alignment, mySettings, Indent.getContinuationIndent(), wrap);
}
else {
- return new SyntheticCodeBlock(createJavaBlocks(subNodes), null, mySettings,
+ return new SyntheticCodeBlock(createJavaBlocks(subNodes), alignment, mySettings,
Indent.getContinuationWithoutFirstIndent(), null);
}
}
import com.intellij.psi.presentation.java.JavaPresentationUtil;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.search.SearchScope;
+import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.RowIcon;
import com.intellij.util.Icons;
private volatile Object myCachedInitializerValue = null; // PsiExpression on constant value for literal
public PsiFieldImpl(final PsiFieldStub stub) {
- super(stub, JavaStubElementTypes.FIELD);
+ this(stub, JavaStubElementTypes.FIELD);
+ }
+
+ protected PsiFieldImpl(final PsiFieldStub stub, final IStubElementType type) {
+ super(stub, type);
}
public PsiFieldImpl(final ASTNode node) {
import com.intellij.psi.presentation.java.JavaPresentationUtil;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.search.SearchScope;
+import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.util.MethodSignature;
import com.intellij.psi.util.MethodSignatureBackedByPsiMethod;
import com.intellij.psi.util.PsiTreeUtil;
private PatchedSoftReference<PsiType> myCachedType = null;
public PsiMethodImpl(final PsiMethodStub stub) {
- super(stub, JavaStubElementTypes.METHOD);
+ this(stub, JavaStubElementTypes.METHOD);
+ }
+
+ protected PsiMethodImpl(final PsiMethodStub stub, final IStubElementType type) {
+ super(stub, type);
}
public PsiMethodImpl(final ASTNode node) {
public static void normalizeBrackets(PsiVariable variable) {
CompositeElement variableElement = (CompositeElement)SourceTreeToPsiMap.psiElementToTree(variable);
- ASTNode type = variableElement.findChildByRole(ChildRole.TYPE);
- LOG.assertTrue(type.getTreeParent() == variableElement);
- ASTNode name = variableElement.findChildByRole(ChildRole.NAME);
+
+ PsiTypeElement typeElement = variable.getTypeElement();
+ PsiIdentifier nameElement = variable.getNameIdentifier();
+ LOG.assertTrue(typeElement != null && nameElement != null);
+
+ ASTNode type = typeElement.getNode();
+ ASTNode name = nameElement.getNode();
ASTNode firstBracket = null;
ASTNode lastBracket = null;
final Language ql = findLanguageByID("JPAQL");
final Language js = findLanguageByID("JavaScript");
if (ql == null || js == null) return;
+ final Language ecma4 = findLanguageByID("ECMA Script Level 4");
final MultiHostInjector myMultiHostInjector = new MultiHostInjector() {
public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
inject(host, placesToInject, js);
return;
}
+ if (ecma4 != null && "ecma4".equals(tag.getLocalName())) {
+ inject(host, placesToInject, ecma4);
+ return;
+ }
if ("jsprefix".equals(tag.getLocalName())) {
inject(host, placesToInject, js, "function foo(doc, window){", "}");
return;
import com.intellij.lang.ASTNode;
import com.intellij.psi.JavaTokenType;
+import com.intellij.psi.PsiClass;
+import com.intellij.psi.PsiField;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.source.Constants;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.tree.ChildRoleBase;
import com.intellij.psi.tree.IElementType;
+import com.intellij.util.CharTable;
import org.jetbrains.annotations.NotNull;
public class FieldElement extends CompositeElement{
return ChildRoleBase.NONE;
}
}
+
+ @Override
+ public ASTNode copyElement() {
+ final CharTable table = SharedImplUtil.findCharTableByTree(this);
+ final PsiClass psiClass = ((PsiField)getPsi()).getContainingClass();
+ return psiClass != null ? ChangeUtil.copyElement(this, psiClass.getTypeParameterList(), table) : super.copyElement();
+ }
}
}
protected void performRefactoring(UsageInfo[] usages) {
- LocalHistoryAction a = LocalHistory.startAction(myProject, getCommandName());
+ LocalHistoryAction a = LocalHistory.getInstance().startAction(getCommandName());
try {
doRefactoring(usages);
}
protected void performRefactoring(UsageInfo[] usages) {
if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, myTargetClass)) return;
- LocalHistoryAction a = LocalHistory.startAction(myProject, getCommandName());
+ LocalHistoryAction a = LocalHistory.getInstance().startAction(getCommandName());
try {
doRefactoring(usages);
}
@Nullable
- public static PsiElement doCopyClasses(final Map<PsiFile, PsiClass[]> classes,
+ public static PsiElement doCopyClasses(final Map<PsiFile, PsiClass[]> fileToClasses,
final String copyClassName,
final PsiDirectory targetDirectory,
final Project project)
throws IncorrectOperationException {
PsiElement newElement = null;
final Map<PsiClass, PsiElement> oldToNewMap = new HashMap<PsiClass, PsiElement>();
- for (PsiClass[] psiClasses : classes.values()) {
+ for (final PsiClass[] psiClasses : fileToClasses.values()) {
for (PsiClass aClass : psiClasses) {
oldToNewMap.put(aClass, null);
}
}
- final PsiFile[] createdFiles = new PsiFile[classes.size()];
+ final PsiFile[] createdFiles = new PsiFile[fileToClasses.size()];
int foIdx = 0;
- for (PsiFile file : classes.keySet()) {
- final String fileName = copyClassName != null ? (copyClassName + "." + file.getViewProvider().getVirtualFile().getExtension()) : file.getName();
- final PsiFile createdFile = targetDirectory.copyFileFrom(fileName, file);
+ for (final Map.Entry<PsiFile, PsiClass[]> entry : fileToClasses.entrySet()) {
+ final PsiFile createdFile = copy(entry.getKey(), targetDirectory, copyClassName);
+ final PsiClass[] sources = entry.getValue();
+
if (createdFile instanceof PsiClassOwner) {
- for (final PsiClass psiClass : ((PsiClassOwner)createdFile).getClasses()) {
- if (!(psiClass instanceof SyntheticElement)) {
- psiClass.getParent().deleteChildRange(psiClass, psiClass);
+ for (final PsiClass destination : ((PsiClassOwner)createdFile).getClasses()) {
+ if (destination instanceof SyntheticElement) {
+ continue;
+ }
+ PsiClass source = findByName(sources, destination.getName());
+ if (source != null) {
+ final PsiClass copy = copy(source, copyClassName);
+ newElement = destination.replace(copy);
+ oldToNewMap.put(source, newElement);
+ }
+ else {
+ destination.delete();
}
}
}
- for (PsiClass aClass : classes.get(file)) {
- final PsiClass classNavigationElement = (PsiClass)aClass.getNavigationElement();
- final PsiClass classCopy = (PsiClass)classNavigationElement.copy();
- if (copyClassName != null) {
- classCopy.setName(copyClassName);
- }
- newElement = createdFile.add(classCopy);
- oldToNewMap.put(aClass, newElement);
- }
createdFiles[foIdx++] = createdFile;
}
return newElement;
}
+ private static PsiFile copy(PsiFile file, PsiDirectory directory, String name) {
+ final String fileName = name != null ? (name + "." + file.getViewProvider().getVirtualFile().getExtension()) : file.getName();
+ return directory.copyFileFrom(fileName, file);
+ }
+
+ private static PsiClass copy(PsiClass aClass, String name) {
+ final PsiClass classNavigationElement = (PsiClass)aClass.getNavigationElement();
+ final PsiClass classCopy = (PsiClass)classNavigationElement.copy();
+ if (name != null) {
+ classCopy.setName(name);
+ }
+ return classCopy;
+ }
+
+ @Nullable
+ private static PsiClass findByName(PsiClass[] classes, String name) {
+ if (name != null) {
+ for (PsiClass aClass : classes) {
+ if (name.equals(aClass.getName())) {
+ return aClass;
+ }
+ }
+ }
+ return null;
+ }
+
private static void rebindExternalReferences(PsiElement element,
Map<PsiClass, PsiElement> oldToNewMap,
Set<PsiElement> rebindExpressions) {
private static PsiClass[] getTopLevelClasses(PsiElement element) {
while (true) {
if (element == null || element instanceof PsiFile) break;
- if (element instanceof PsiClass && element.getParent() instanceof PsiFile) break;
+ if (element instanceof PsiClass && element.getParent() != null && (((PsiClass)element).getContainingClass() == null)) break;
element = element.getParent();
}
if (element instanceof PsiClassOwner) {
private void doRefactoring() throws IncorrectOperationException {
- LocalHistoryAction a = LocalHistory.startAction(myProject, getCommandName());
+ LocalHistoryAction a = LocalHistory.getInstance().startAction(getCommandName());
PsiClass anInterface = null;
try {
anInterface = extractInterface(myTargetDir, myClass, myInterfaceName, mySelectedMembers, myJavaDocPolicy);
final PsiDirectory targetDirectory = dialog.getTargetDirectory();
final MemberInfo[] selectedMemberInfos = dialog.getSelectedMemberInfos();
final DocCommentPolicy javaDocPolicy = new DocCommentPolicy(dialog.getJavaDocPolicy());
- LocalHistoryAction a = LocalHistory.startAction(myProject, getCommandName(subclass, superclassName));
+ LocalHistoryAction a = LocalHistory.getInstance().startAction(getCommandName(subclass, superclassName));
try {
PsiClass superclass = null;
if (!myIsInnerClassNeeded) return;
PsiClass innerClass = myFactory.createClass(myInnerClassName);
- final PsiJavaCodeReferenceElement baseClassReferenceElement = myFactory.createClassReferenceElement(myBaseClass);
+ final PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(myBaseClass, myClass, PsiSubstitutor.EMPTY);
+ final PsiClassType superClassType = myFactory.createType(myBaseClass, superClassSubstitutor);
+ final PsiJavaCodeReferenceElement baseClassReferenceElement = myFactory.createReferenceElementByType(superClassType);
if (!myBaseClass.isInterface()) {
innerClass.getExtendsList().add(baseClassReferenceElement);
} else {
myEditor.getCaretModel().moveToLogicalPosition(pos);
}
- LocalHistoryAction a = LocalHistory.startAction(myProject, getCommandName());
+ LocalHistoryAction a = LocalHistory.getInstance().startAction(getCommandName());
try {
doRefactoring(usages);
}
ElementToWorkOn.processElementToWorkOn(editor, file, REFACTORING_NAME, getHelpID(), project, getElementProcessor(project, editor));
}
- protected boolean invokeImpl(Project project, final PsiLocalVariable localVariable, Editor editor) {
- final LocalToFieldHandler localToFieldHandler = new LocalToFieldHandler(project, true);
+ protected boolean invokeImpl(final Project project, final PsiLocalVariable localVariable, final Editor editor) {
+ final LocalToFieldHandler localToFieldHandler = new LocalToFieldHandler(project, true){
+ @Override
+ protected Settings showRefactoringDialog(PsiClass aClass,
+ PsiLocalVariable local,
+ PsiExpression[] occurences,
+ boolean isStatic) {
+ return IntroduceConstantHandler.this.showRefactoringDialog(project, editor, aClass, local.getInitializer(), local.getType(), occurences, null, null);
+ }
+ };
return localToFieldHandler.convertLocalToField(localVariable, editor);
}
}
}
- IntroduceConstantDialog dialog =
+ final IntroduceConstantDialog dialog =
new IntroduceConstantDialog(project, parentClass, expr, localVariable, false, occurences, getParentClass(),
new TypeSelectorManagerImpl(project, type, expr, occurences));
dialog.show();
return new ExpressionOccurenceManager(selectedExpr, parentClass, occurenceFilter, true);
}
- protected boolean invokeImpl(Project project, PsiLocalVariable localVariable, Editor editor) {
- LocalToFieldHandler localToFieldHandler = new LocalToFieldHandler(project, false);
+ protected boolean invokeImpl(final Project project, PsiLocalVariable localVariable, final Editor editor) {
+ LocalToFieldHandler localToFieldHandler = new LocalToFieldHandler(project, false){
+ @Override
+ protected Settings showRefactoringDialog(PsiClass aClass,
+ PsiLocalVariable local,
+ PsiExpression[] occurences,
+ boolean isStatic) {
+ final PsiStatement statement = PsiTreeUtil.getParentOfType(local, PsiStatement.class);
+ return IntroduceFieldHandler.this.showRefactoringDialog(project, editor, aClass, local.getInitializer(), local.getType(), occurences, statement, statement);
+ }
+ };
return localToFieldHandler.convertLocalToField(localVariable, editor);
}
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
-import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.RefactoringBundle;
-import com.intellij.refactoring.ui.TypeSelectorManagerImpl;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.EnumConstantsUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import static com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler.InitializationPlace.IN_CONSTRUCTOR;
import static com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION;
-public class LocalToFieldHandler {
+public abstract class LocalToFieldHandler {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.introduceField.LocalToFieldHandler");
private static final String REFACTORING_NAME = RefactoringBundle.message("convert.local.to.field.title");
myIsConstant = isConstant;
}
- protected BaseExpressionToFieldHandler.Settings showRefactoringDialog(PsiClass aClass, PsiLocalVariable local, PsiExpression[] occurences, boolean isStatic) {
- final String fieldName;
- final BaseExpressionToFieldHandler.InitializationPlace initializerPlace;
- final boolean declareFinal;
- @Modifier String fieldVisibility;
- final TypeSelectorManagerImpl typeSelectorManager = new TypeSelectorManagerImpl(myProject, local.getType(),
- occurences
- );
-
- final boolean annotateAsNonNls;
- final boolean introduceEnumConstant;
- if (myIsConstant) {
- IntroduceConstantDialog dialog = new IntroduceConstantDialog(myProject, aClass,
- local.getInitializer(), local, true, occurences, aClass, typeSelectorManager
- );
- dialog.show();
- if (!dialog.isOK()) return null;
- fieldName = dialog.getEnteredName();
- declareFinal = true;
- initializerPlace = IN_FIELD_DECLARATION;
- fieldVisibility = dialog.getFieldVisibility();
- annotateAsNonNls = dialog.isAnnotateAsNonNls();
- introduceEnumConstant = dialog.introduceEnumConstant();
- }
- else {
- PsiMethod method = PsiTreeUtil.getParentOfType(local, PsiMethod.class);
- IntroduceFieldDialog dialog = new IntroduceFieldDialog(myProject, aClass,
- local.getInitializer(), local,
- method != null && method.isConstructor(),
- true, isStatic,
- occurences.length, method != null, method != null,
- typeSelectorManager
- );
- dialog.show();
- if (!dialog.isOK()) return null;
- fieldName = dialog.getEnteredName();
- initializerPlace = dialog.getInitializerPlace();
- declareFinal = dialog.isDeclareFinal();
- fieldVisibility = dialog.getFieldVisibility();
- annotateAsNonNls = false;
- introduceEnumConstant = false;
- }
-
- return new BaseExpressionToFieldHandler.Settings(fieldName, true, isStatic, declareFinal, initializerPlace, fieldVisibility, local, null, true, new BaseExpressionToFieldHandler.TargetDestination(aClass), annotateAsNonNls,
- introduceEnumConstant);
- }
+ protected abstract BaseExpressionToFieldHandler.Settings showRefactoringDialog(PsiClass aClass, PsiLocalVariable local, PsiExpression[] occurences, boolean isStatic);
public boolean convertLocalToField(final PsiLocalVariable local, final Editor editor) {
PsiClass aClass;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.OverridingMethodsSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
-import com.intellij.psi.util.InheritanceUtil;
-import com.intellij.psi.util.MethodSignatureUtil;
-import com.intellij.psi.util.PsiTreeUtil;
-import com.intellij.psi.util.PsiUtil;
+import com.intellij.psi.util.*;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.listeners.JavaRefactoringListenerManager;
ChangeContextUtil.encodeContextInfo(info.getMember(), true);
}
+ final PsiSubstitutor substitutor = upDownSuperClassSubstitutor();
+ final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject);
+
// do actual move
for (MemberInfo info : myMembersToMove) {
if (info.getMember() instanceof PsiMethod) {
PsiMethod methodCopy = (PsiMethod)method.copy();
ChangeContextUtil.clearContextInfo(method);
RefactoringUtil.abstractizeMethod(myTargetSuperClass, methodCopy);
-
+ RefactoringUtil.replaceMovedMemberTypeParameters(methodCopy, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
if (method.findDeepestSuperMethods().length == 0 || (myTargetSuperClass.isInterface() && !PsiUtil.isLanguageLevel6OrHigher(mySourceClass))) {
deleteOverrideAnnotationIfFound(methodCopy);
}
if (isOriginalMethodAbstract) {
PsiUtil.setModifierProperty(myTargetSuperClass, PsiModifier.ABSTRACT, true);
}
+ RefactoringUtil.replaceMovedMemberTypeParameters(method, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
fixReferencesToStatic(method, movedMembers);
final PsiMethod superClassMethod = myTargetSuperClass.findMethodBySignature(method, false);
if (superClassMethod != null && superClassMethod.hasModifierProperty(PsiModifier.ABSTRACT)) {
else if (info.getMember() instanceof PsiField) {
PsiField field = (PsiField)info.getMember();
field.normalizeDeclaration();
+ RefactoringUtil.replaceMovedMemberTypeParameters(field, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
fixReferencesToStatic(field, movedMembers);
if (myIsTargetInterface) {
PsiUtil.setModifierProperty(field, PsiModifier.PUBLIC, true);
RefactoringUtil.removeFromReferenceList(sourceReferenceList, aClass) :
RefactoringUtil.findReferenceToClass(sourceReferenceList, aClass);
if (ref != null) {
+ RefactoringUtil.replaceMovedMemberTypeParameters(ref, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
final PsiReferenceList referenceList =
myTargetSuperClass.isInterface() ? myTargetSuperClass.getExtendsList() : myTargetSuperClass.getImplementsList();
assert referenceList != null;
}
}
else {
+ RefactoringUtil.replaceMovedMemberTypeParameters(aClass, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
fixReferencesToStatic(aClass, movedMembers);
final PsiMember movedElement = (PsiMember)myTargetSuperClass.add(aClass);
myMembersAfterMove.add(movedElement);
}
}
+ private PsiSubstitutor upDownSuperClassSubstitutor() {
+ PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
+ for (PsiTypeParameter parameter : PsiUtil.typeParametersIterable(mySourceClass)) {
+ substitutor = substitutor.put(parameter, null);
+ }
+ final Map<PsiTypeParameter, PsiType> substitutionMap =
+ TypeConversionUtil.getSuperClassSubstitutor(myTargetSuperClass, mySourceClass, PsiSubstitutor.EMPTY).getSubstitutionMap();
+ for (PsiTypeParameter parameter : substitutionMap.keySet()) {
+ final PsiType type = substitutionMap.get(parameter);
+ final PsiClass resolvedClass = PsiUtil.resolveClassInType(type);
+ if (resolvedClass instanceof PsiTypeParameter) {
+ substitutor = substitutor.put((PsiTypeParameter)resolvedClass, JavaPsiFacade.getElementFactory(myProject).createType(parameter));
+ }
+ }
+ return substitutor;
+ }
+
private static void deleteOverrideAnnotationIfFound(PsiMethod oMethod) {
final PsiAnnotation annotation = AnnotationUtil.findAnnotation(oMethod, Override.class.getName());
if (annotation != null) {
private void pushDownToClass(PsiClass targetClass) throws IncorrectOperationException {
final PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory();
final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(myClass, targetClass, PsiSubstitutor.EMPTY);
- for (PsiTypeParameter parameter : PsiUtil.typeParametersIterable(myClass)) {
- for (PsiReference reference : ReferencesSearch.search(parameter)) {
- final PsiElement element = reference.getElement();
- final PsiMember member = PsiTreeUtil.getParentOfType(element, PsiMember.class);
- if (member != null) {
- for (MemberInfo memberInfo : myMemberInfos) {
- if (PsiTreeUtil.isAncestor(memberInfo.getMember(), member, false)) {
- PsiType substitutedType = substitutor.substitute(parameter);
- if (substitutedType == null) {
- substitutedType = TypeConversionUtil.erasure(factory.createType(parameter));
- }
- element.getParent().replace(factory.createTypeElement(substitutedType));
- break;
- }
- }
- }
- }
- }
for (MemberInfo memberInfo : myMemberInfos) {
- final PsiMember member = memberInfo.getMember();
+ PsiMember member = memberInfo.getMember();
final List<PsiReference> refsToRebind = new ArrayList<PsiReference>();
final PsiModifierList list = member.getModifierList();
LOG.assertTrue(list != null);
refsToRebind.add(reference);
}
}
-
+ member = (PsiMember)member.copy();
+ RefactoringUtil.replaceMovedMemberTypeParameters(member, PsiUtil.typeParametersIterable(myClass), substitutor, factory);
PsiMember newMember = null;
if (member instanceof PsiField) {
((PsiField)member).normalizeDeclaration();
protected void performRefactoring(UsageInfo[] usages) {
PsiManager psiManager = PsiManager.getInstance(myProject);
final PsiMigration psiMigration = JavaPsiFacade.getInstance(psiManager.getProject()).startMigration();
- LocalHistoryAction a = LocalHistory.startAction(myProject, getCommandName());
+ LocalHistoryAction a = LocalHistory.getInstance().startAction(getCommandName());
try {
for (int i = 0; i < myMigrationMap.getEntryCount(); i++) {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
- LocalHistoryAction a = LocalHistory.startAction(project, commandDescription);
+ LocalHistoryAction a = LocalHistory.getInstance().startAction(commandDescription);
try {
rearrangeDirectoriesToTarget(directories, selectedTarget);
}
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
LOG.assertTrue(newElement != null);
final PsiReference reference = moveRenameUsage.getReference();
if (reference != null) {
- reference.bindToElement(newElement);
+ try {
+ reference.bindToElement(newElement);
+ } catch (IncorrectOperationException e) {//
+ }
}
}
}
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
+import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.refactoring.PackageWrapper;
import com.intellij.refactoring.introduceField.ElementToWorkOn;
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
return null;
}
+ public static void replaceMovedMemberTypeParameters(final PsiElement member,
+ final Iterable<PsiTypeParameter> parametersIterable,
+ final PsiSubstitutor substitutor,
+ final PsiElementFactory factory) {
+ for (PsiTypeParameter parameter : parametersIterable) {
+ for (PsiReference reference : ReferencesSearch.search(parameter, new LocalSearchScope(member))) {
+ final PsiElement element = reference.getElement();
+ PsiType substitutedType = substitutor.substitute(parameter);
+ if (substitutedType == null) {
+ substitutedType = TypeConversionUtil.erasure(factory.createType(parameter));
+ }
+ element.getParent().replace(factory.createTypeElement(substitutedType));
+ }
+ }
+ }
+
public static interface ImplicitConstructorUsageVisitor {
void visitConstructor(PsiMethod constructor, PsiMethod baseConstructor);
}
private static void replaceDuplicate(final Project project, final List<Match> duplicates, final PsiMethod method) {
- LocalHistoryAction a = LocalHistory.startAction(project, REFACTORING_NAME);
+ LocalHistoryAction a = LocalHistory.getInstance().startAction(REFACTORING_NAME);
try {
final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
if (progressIndicator != null && progressIndicator.isCanceled()) return;
--- /dev/null
+public enum ButtonKey {
+ CANCEL_ALL,
+ CANCEL_SELL;
+
+ public static final ButtonKey[] ARR = {CANCEL_ALL, CANCEL_S<caret>};
+}
\ No newline at end of file
--- /dev/null
+public enum ButtonKey {
+ CANCEL_ALL,
+ CANCEL_SELL;
+
+ public static final ButtonKey[] ARR = {CANCEL_ALL, CANCEL_SELL<caret>};
+}
\ No newline at end of file
--- /dev/null
+public class Foo {
+ Object foo(bo<caret>){ }
+}
--- /dev/null
+public class Foo {
+ Object foo(boolean <caret>){ }
+}
--- /dev/null
+public class Main {
+
+ public void main(String[] args) {
+ Aaaa a = new Bbbb(<caret>2);
+ }
+
+ class Aaaa {
+ int aaa;
+
+ Aaaa(int aaa) {
+ this.aaa = aaa;
+ }
+ }
+
+ class Bbbb extends Aaaa{
+ Bbbb(int aaa) {
+ super(aaa);
+ }
+ }
+
+}
--- /dev/null
+public class Main {
+
+ public void main(String[] args) {
+ Aaaa a = new B<caret>Aaaa(2);
+ }
+
+ class Aaaa {
+ int aaa;
+
+ Aaaa(int aaa) {
+ this.aaa = aaa;
+ }
+ }
+
+ class Bbbb extends Aaaa{
+ Bbbb(int aaa) {
+ super(aaa);
+ }
+ }
+
+}
* at least as large as the list size. As elements are added to an ArrayList,
* its capacity grows automatically. The details of the growth policy are not
* specified beyond the fact that adding an element has constant amortized
- * time cost.<p>
+ * time cost.<p>
*
* An application can increase the capacity of an <tt>ArrayList</tt> instance
* before adding a large number of elements using the <tt>ensureCapacity</tt>
* Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
- * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
+ * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i><p>
*
- * This class is a member of the
+ * This class is a member of the
* <a href="{@docRoot}/../guide/collections/index.html">
* Java Collections Framework</a>.
*
size = c.size();
// Allow 10% room for growth
elementData = (E[])new Object[
- (int)Math.min((size*110L)/100,Integer.MAX_VALUE)];
+ (int)Math.min((size*110L)/100,Integer.MAX_VALUE)];
c.toArray(elementData);
}
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
- * specified by the minimum capacity argument.
+ * specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity.
*/
}
/**
- * Searches for the first occurence of the given argument, testing
- * for equality using the <tt>equals</tt> method.
+ * Searches for the first occurence of the given argument, testing
+ * for equality using the <tt>equals</tt> method.
*
* @param elem an object.
* @return the index of the first occurrence of the argument in this
* @return a clone of this <tt>ArrayList</tt> instance.
*/
public Object clone() {
- try {
+ try {
Bar<E> v = (Bar<E>) super.clone();
v.elementData = (E[])new Object[size];
System.arraycopy(elementData, 0, v.elementData, 0, size);
v.modCount = 0;
return v;
- } catch (CloneNotSupportedException e) {
+ } catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
- System.arraycopy(elementData, index+1, elementData, index,
+ System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}
for (int i=0; i<size; i++)
a[i] = s.readObject();
}
-}
\ No newline at end of file
+}
--- /dev/null
+public class A {
+ public final MyIntf myDelegate = new MyIntf();
+
+ private class MyIntf implements Intf<Integer> {
+ public void method1(Integer t) {
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+public interface Intf<T> {
+ void method1(T t);
+}
\ No newline at end of file
--- /dev/null
+public class A implements Intf<Integer> {
+ public void method1(Integer t) {
+ }
+}
\ No newline at end of file
--- /dev/null
+public interface Intf<T> {
+ void method1(T t);
+}
\ No newline at end of file
--- /dev/null
+class Test {
+ Integer t;
+}
\ No newline at end of file
--- /dev/null
+class Test1 {
+ String t;
+}
\ No newline at end of file
--- /dev/null
+class Super<T> {
+ T t;
+}
\ No newline at end of file
--- /dev/null
+class Test extends Super<Integer>{
+}
\ No newline at end of file
--- /dev/null
+class Test1 extends Super<String>{
+}
\ No newline at end of file
--- /dev/null
+public abstract class Parent<S> {}
+
+class Child<T> extends Parent<T> {
+ void <caret>method(T t){}
+}
--- /dev/null
+public abstract class Parent<S> {
+ abstract void method(S t);
+}
+
+class Child<T> extends Parent<T> {
+ @Override
+ void method(T t){}
+}
--- /dev/null
+public class Parent<S> {}
+
+interface I<IT> {
+ void method(IT t);
+}
+
+class Child<T> extends Parent<T> implements I<T>{
+ <caret>
+ public void method(T t){}
+}
--- /dev/null
+public class Parent<S> implements I<S> {}
+
+interface I<IT> {
+ void method(IT t);
+}
+
+class Child<T> extends Parent<T> {
+
+ public void method(T t){}
+}
--- /dev/null
+public class Parent<S> {}
+
+class Child extends Parent<String> {
+ String <caret>f;
+}
--- /dev/null
+public class Parent<S> {
+ String f;
+}
+
+class Child extends Parent<String> {
+}
--- /dev/null
+public class Parent {}
+
+class Child<T> extends Parent {
+ T <caret>f;
+}
--- /dev/null
+public class Parent {
+ Object f;
+}
+
+class Child<T> extends Parent {
+}
--- /dev/null
+public class Parent<S> {}
+
+class Child<T> extends Parent<T> {
+ T <caret>f;
+}
--- /dev/null
+public class Parent<S> {
+ S f;
+}
+
+class Child<T> extends Parent<T> {
+}
public void testMethodParameterAnnotationClass() throws Throwable { doTest(); }
+ public void testEnumConstantFromEnumMember() throws Throwable { doTest(); }
+
+ public void testPrimitiveMethodParameter() throws Throwable { doTest(); }
+
}
checkResultByTestName();
}
+ public void testTabAfterNew() throws Exception {
+ configureByTestName();
+ select('\t');
+ checkResultByTestName();
+ }
+
private void doTest(boolean performAction, boolean selectItem) throws Exception {
configureByTestName();
if (performAction) {
new String[]{"getDate"}, ArrayUtil.EMPTY_STRING_ARRAY, false, false));
}
+ public void testTypeParametersSubstitution() throws Exception {
+ doTest(createPerformAction("A", "myDelegate", "MyIntf", "Intf", new int[]{}, ArrayUtil.EMPTY_STRING_ARRAY, true, false));
+ }
private PerformAction createPerformAction(
final String className, final String fieldName, final String innerClassName,
}
public void testMultipleSubclasses() throws Exception {
+ doTestMultipleSubclasses();
+ }
+
+ public void testMultipleSubstitutions() throws Exception {
+ doTestMultipleSubclasses();
+ }
+
+ private void doTestMultipleSubclasses() throws Exception {
doTest(new PerformAction() {
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
PsiClass superClass = myJavaFacade.findClass("Super", GlobalSearchScope.allScope(myProject));
doTest(new MemberDescriptor ("get", PsiMethod.class));
}
+ public void testTypeParamErasure() throws Exception {
+ doTest(new MemberDescriptor("f", PsiField.class));
+ }
+
+ public void testTypeParamSubst() throws Exception {
+ doTest(new MemberDescriptor("f", PsiField.class));
+ }
+
+ public void testTypeArgument() throws Exception {
+ doTest(new MemberDescriptor("f", PsiField.class));
+ }
+
+ public void testGenericsInAbstractMethod() throws Exception {
+ doTest(new MemberDescriptor("method", PsiMethod.class, true));
+ }
+
+ public void testGenericsInImplements() throws Exception {
+ doTest(false, new MemberDescriptor("I", PsiClass.class));
+ }
+
private void doTest(MemberDescriptor... membersToFind) throws Exception {
+ doTest(true, membersToFind);
+ }
+
+ private void doTest(final boolean checkMemebersMovedCount, MemberDescriptor... membersToFind) throws Exception {
configureByFile(BASE_PATH + getTestName(false) + ".java");
PsiElement elementAt = getFile().findElementAt(getEditor().getCaretModel().getOffset());
final PsiClass sourceClass = PsiTreeUtil.getParentOfType(elementAt, PsiClass.class);
final PullUpHelper helper = new PullUpHelper(sourceClass, targetClass, infos, new DocCommentPolicy(DocCommentPolicy.ASIS));
helper.run();
JavaRefactoringListenerManager.getInstance(getProject()).removeMoveMembersListener(listener);
- assertEquals(countMoved[0], membersToFind.length);
+ if (checkMemebersMovedCount) {
+ assertEquals(countMoved[0], membersToFind.length);
+ }
checkResultByFile(BASE_PATH + getTestName(false) + "_after.java");
}
--- /dev/null
+/*
+ * 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.execution.runners;
+
+import com.intellij.execution.ExecutionBundle;
+import com.intellij.execution.ExecutionException;
+import com.intellij.execution.RunCanceledByUserException;
+import com.intellij.execution.configurations.RunProfile;
+import com.intellij.execution.process.ProcessNotCreatedException;
+import com.intellij.ide.util.PropertiesComponent;
+import com.intellij.notification.*;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.project.Project;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import javax.swing.event.HyperlinkEvent;
+
+public class ExecutionUtil {
+ public static final String NOTIFICATION_GROUP_ID = "Execution";
+
+ private static final Logger LOG = Logger.getInstance("com.intellij.execution.runners.ExecutionUtil");
+
+ private ExecutionUtil() {
+ }
+
+ public static void handleExecutionError(final Project project, @NotNull String taskName, final ExecutionException e) {
+ if (e instanceof RunCanceledByUserException) return;
+
+ String title = ExecutionBundle.message("error.running.configuration.with.error.error.message", taskName);
+ String message = e.getMessage();
+ NotificationDisplayType type = NotificationDisplayType.BALLOON;
+ NotificationListener listener = null;
+
+ if (ApplicationManager.getApplication().isUnitTestMode()) {
+ LOG.error(message + ":" + message);
+ }
+ else {
+ if (message.contains("87") && e instanceof ProcessNotCreatedException) {
+ final String commandLineString = ((ProcessNotCreatedException)e).getCommandLine().getCommandLineString();
+ if (commandLineString.length() > 1024 * 32) {
+ type = NotificationDisplayType.STICKY_BALLOON;
+ message += "\n" +
+ "Command line is too long. In order to reduce its length classpath file can be used.<br>" +
+ "Would you like to enable classpath file mode for all run configurations of your project?<br>" +
+ "<a href=\"\">Enable</a>";
+
+ listener = new NotificationListener() {
+ public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) {
+ PropertiesComponent.getInstance(project).setValue("dynamic.classpath", "true");
+ notification.expire();
+ }
+ };
+ }
+ }
+ }
+ Notification n = new Notification(NOTIFICATION_GROUP_ID, title, message, NotificationType.ERROR, listener);
+ Notifications.Bus.notify(n, type, project);
+ }
+
+ public static void handleExecutionError(final Project project, @NotNull final RunProfile runProfile, final ExecutionException e) {
+ handleExecutionError(project, runProfile.getName(), e);
+ }
+}
package com.intellij.execution.runners;
-import com.intellij.execution.ExecutionException;
-import com.intellij.execution.ExecutionManager;
-import com.intellij.execution.ExecutionResult;
-import com.intellij.execution.Executor;
+import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.history.LocalHistory;
-import com.intellij.history.LocalHistoryConfiguration;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DataKey;
import com.intellij.openapi.application.ApplicationManager;
if (callback != null) callback.processStarted(descriptor);
if (descriptor != null) {
- if (LocalHistoryConfiguration.getInstance().ADD_LABEL_ON_RUNNING) {
- LocalHistory.putSystemLabel(project, executor.getId() + " " + profile.getName());
- }
+ LocalHistory.getInstance().putSystemLabel(project, getLocalHistoryLabel(profile, state));
ExecutionManager.getInstance(project).getContentManager().showRunContent(executor, descriptor);
final ProcessHandler processHandler = descriptor.getProcessHandler();
}
}
catch (ExecutionException e) {
- ProgramRunnerUtil.handleExecutionError(project, profile, e);
+ ExecutionUtil.handleExecutionError(project, profile, e);
}
}
};
protected abstract RunContentDescriptor doExecute(final Project project, final Executor executor, final RunProfileState state,
final RunContentDescriptor contentToReuse,
final ExecutionEnvironment env) throws ExecutionException;
+
+ protected String getLocalHistoryLabel(RunProfile profile, RunProfileState state) {
+ return ExecutionBundle.message("default.runner.start.action.label", profile.getName());
+ }
}
+++ /dev/null
-/*
- * 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.execution.runners;
-
-import com.intellij.execution.ExecutionBundle;
-import com.intellij.execution.ExecutionException;
-import com.intellij.execution.RunCanceledByUserException;
-import com.intellij.execution.configurations.RunProfile;
-import com.intellij.execution.process.ProcessNotCreatedException;
-import com.intellij.ide.util.PropertiesComponent;
-import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.project.Project;
-import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.ui.Messages;
-
-/**
- * @author spleaner
- */
-public class ProgramRunnerUtil {
- private static final Logger LOG = Logger.getInstance("com.intellij.execution.runners.ProgramRunnerUtil");
-
- private ProgramRunnerUtil() {
- }
-
- public static void handleExecutionError(final Project project, final RunProfile runProfile, final ExecutionException e) {
- if (e instanceof RunCanceledByUserException) {
- return;
- }
-
- String message = ExecutionBundle.message("error.running.configuration.with.error.error.message", runProfile != null? runProfile.getName() : "Run profile", e.getMessage());
- if (ApplicationManager.getApplication().isUnitTestMode()) {
- LOG.error(message);
- }
- else {
- if (message.contains("87") && e instanceof ProcessNotCreatedException) {
- final String commandLineString = ((ProcessNotCreatedException)e).getCommandLine().getCommandLineString();
- if (commandLineString.length() > 1024 * 32) {
- if (Messages.showYesNoDialog(project, message + "\nCommand line is too long. In order to reduce its length classpath file can be used. Would you like to enable classpath file mode for all run configurations of your project?", ExecutionBundle.message("run.error.message.title"), Messages.getErrorIcon()) ==
- DialogWrapper.OK_EXIT_CODE) {
- PropertiesComponent.getInstance(project).setValue("dynamic.classpath", "true");
- return;
- }
- }
- }
- Messages.showErrorDialog(project, message, ExecutionBundle.message("run.error.message.title"));
- }
- }
-
-}
+++ /dev/null
-/*
- * 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.execution.ui;
-
-import com.intellij.execution.filters.Filter;
-import com.intellij.execution.filters.HyperlinkInfo;
-import com.intellij.execution.process.ProcessHandler;
-import com.intellij.openapi.actionSystem.AnAction;
-import org.jetbrains.annotations.NotNull;
-
-import javax.swing.*;
-
-/**
- * @author Gregory.Shrago
- */
-public class ConsoleViewWrapper implements ConsoleView, ExecutionConsoleEx {
- private final ConsoleView myDelegate;
-
- public ConsoleViewWrapper(final ConsoleView delegate) {
- myDelegate = delegate;
- }
-
- public ConsoleView getDelegate() {
- return myDelegate;
- }
-
- public void dispose() {
- myDelegate.dispose();
- }
-
- public JComponent getComponent() {
- return myDelegate.getComponent();
- }
-
- public JComponent getPreferredFocusableComponent() {
- return myDelegate.getPreferredFocusableComponent();
- }
-
- public void print(String s, ConsoleViewContentType contentType) {
- myDelegate.print(s, contentType);
- }
-
- public void clear() {
- myDelegate.clear();
- }
-
- public void scrollTo(int offset) {
- myDelegate.scrollTo(offset);
- }
-
- public void attachToProcess(ProcessHandler processHandler) {
- myDelegate.attachToProcess(processHandler);
- }
-
- public void setOutputPaused(boolean value) {
- myDelegate.setOutputPaused(value);
- }
-
- public boolean isOutputPaused() {
- return myDelegate.isOutputPaused();
- }
-
- public boolean hasDeferredOutput() {
- return myDelegate.hasDeferredOutput();
- }
-
- public void performWhenNoDeferredOutput(Runnable runnable) {
- myDelegate.performWhenNoDeferredOutput(runnable);
- }
-
- public void setHelpId(String helpId) {
- myDelegate.setHelpId(helpId);
- }
-
- public void addMessageFilter(Filter filter) {
- myDelegate.addMessageFilter(filter);
- }
-
- public void printHyperlink(String hyperlinkText, HyperlinkInfo info) {
- myDelegate.printHyperlink(hyperlinkText, info);
- }
-
- public int getContentSize() {
- return myDelegate.getContentSize();
- }
-
- public boolean canPause() {
- return myDelegate.canPause();
- }
-
- public void buildUi(RunnerLayoutUi layoutUi) {
- if (myDelegate instanceof ExecutionConsoleEx) {
- ((ExecutionConsoleEx)myDelegate).buildUi(layoutUi);
- }
- }
-
-
- public String getExecutionConsoleId() {
- if (myDelegate instanceof ExecutionConsoleEx) {
- return ((ExecutionConsoleEx)myDelegate).getExecutionConsoleId();
- }
- return null;
- }
-
- @NotNull
- public AnAction[] createConsoleActions() {
- return myDelegate.createConsoleActions();
- }
-
-}
protected void run(Result result) throws Throwable {
LocalHistoryAction action = LocalHistoryAction.NULL;
try {
- action = LocalHistory.startAction(myProject, commandName);
+ action = LocalHistory.getInstance().startAction(commandName);
PsiElement[] psiElements = create(inputString);
myCreatedElements[0] = new SmartPsiElementPointer[psiElements.length];
return null;
}
+ public void onFrameworkSelectionChanged(boolean selected) {
+ }
+
public void addListener(@NotNull FrameworkSupportConfigurableListener listener) {
myDispatcher.addListener(listener);
}
public boolean isCollapsedByDefault(@NotNull ASTNode node) {
final FoldingBuilder builder = node.getUserData(FOLDING_BUILDER);
- return builder == null ? false : builder.isCollapsedByDefault(node);
+ return builder != null && builder.isCollapsedByDefault(node);
}
}
import com.intellij.lang.ASTNode;
import com.intellij.lang.Language;
-import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.editor.FoldingGroup;
import com.intellij.openapi.util.ProperTextRange;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiFile;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
* Returns the folded text range.
* @return the folded text range.
*/
+ @NotNull
public TextRange getRange() {
- return getRange(myElement, myRange);
- }
-
- public static TextRange getRange(ASTNode node, TextRange range) {
- PsiElement element = node.getPsi();
- PsiFile containingFile = element.getContainingFile();
- InjectedLanguageManager injectedManager = InjectedLanguageManager.getInstance(containingFile.getProject());
- boolean isInjected = injectedManager.isInjectedFragment(containingFile);
- if (isInjected) {
- range = injectedManager.injectedToHost(element, range);
- }
- return range;
+ return myRange;
}
@Nullable
public boolean SPECIAL_ELSE_IF_TREATMENT = true;
+ /**
+ * Indicates if long sequence of chained method calls should be aligned.
+ * <p/>
+ * E.g. if statement like <code>'foo.bar().bar().bar();'</code> should be reformatted to the one below if,
+ * say, last <code>'bar()'</code> call exceeds right margin. The code looks as follows after reformatting
+ * if this property is <code>true</code>:
+ * <p/>
+ * <pre>
+ * foo.bar().bar()
+ * .bar();
+ * </pre>
+ */
+ public boolean ALIGN_MULTILINE_CHAINED_METHODS = false;
public boolean ALIGN_MULTILINE_PARAMETERS = true;
public boolean ALIGN_MULTILINE_PARAMETERS_IN_CALLS = false;
public boolean ALIGN_MULTILINE_FOR = true;
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
+ ApplicationManager.getApplication().getMessageBus().syncPublisher(VirtualFileManager.VFS_CHANGES)
+ .before(new ArrayList<VFileEvent>(list));
ApplicationManager.getApplication().getMessageBus().syncPublisher(VirtualFileManager.VFS_CHANGES)
.after(new ArrayList<VFileEvent>(list));
}
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
-import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.OptionGroup;
import javax.swing.*;
private JComboBox myWhileForceCombo;
private JComboBox myDoWhileForceCombo;
+ private JCheckBox myAlignChainedMethods;
private JCheckBox myAlignDeclarationParameters;
private JCheckBox myAlignCallParameters;
private JCheckBox myAlignExtendsList;
public CodeStyleIndentAndBracesPanel(CodeStyleSettings settings) {
super(settings);
- myPanel.add(createKeepWhenReformatingPanel(),
+ myPanel.add(createKeepWhenReformattingPanel(),
new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(0, 4, 0, 4), 0, 0));
return LanguageCodeStyleSettingsProvider.SettingsType.INDENT_AND_BRACES_SETTINGS;
}
- private Component createKeepWhenReformatingPanel() {
+ private Component createKeepWhenReformattingPanel() {
OptionGroup optionGroup = new OptionGroup(ApplicationBundle.message("title.keep.when.reformatting"));
myKeepLineBreaks = createCheckBox(ApplicationBundle.message("checkbox.keep.when.reformatting.line.breaks"));
private JPanel createAlignmentsPanel() {
OptionGroup optionGroup = new OptionGroup(ApplicationBundle.message("title.align.when.multiline"));
+ myAlignChainedMethods = createCheckBox(ApplicationBundle.message("checkbox.align.multiline.chained.methods"));
+ optionGroup.add(myAlignChainedMethods);
+
myAlignDeclarationParameters = createCheckBox(ApplicationBundle.message("checkbox.align.multiline.method.parameters"));
optionGroup.add(myAlignDeclarationParameters);
isModified |= settings.CLASS_BRACE_STYLE != getBraceComboValue(myClassDeclarationCombo);
isModified |= settings.METHOD_BRACE_STYLE != getBraceComboValue(myMethodDeclarationCombo);
+ isModified |= isModified(myAlignChainedMethods, settings.ALIGN_MULTILINE_CHAINED_METHODS);
isModified |= isModified(myAlignAssignment, settings.ALIGN_MULTILINE_ASSIGNMENT);
isModified |= isModified(myAlignBinaryExpression, settings.ALIGN_MULTILINE_BINARY_OPERATION);
isModified |= isModified(myAlignCallParameters, settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
myAlignAssignment.setSelected(settings.ALIGN_MULTILINE_ASSIGNMENT);
myAlignBinaryExpression.setSelected(settings.ALIGN_MULTILINE_BINARY_OPERATION);
myAlignCallParameters.setSelected(settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
+ myAlignChainedMethods.setSelected(settings.ALIGN_MULTILINE_CHAINED_METHODS);
myAlignDeclarationParameters.setSelected(settings.ALIGN_MULTILINE_PARAMETERS);
myAlignExtendsList.setSelected(settings.ALIGN_MULTILINE_EXTENDS_LIST);
myAlignForStatement.setSelected(settings.ALIGN_MULTILINE_FOR);
settings.ALIGN_MULTILINE_ASSIGNMENT = myAlignAssignment.isSelected();
settings.ALIGN_MULTILINE_BINARY_OPERATION = myAlignBinaryExpression.isSelected();
settings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS = myAlignCallParameters.isSelected();
+ settings.ALIGN_MULTILINE_CHAINED_METHODS = myAlignChainedMethods.isSelected();
settings.ALIGN_MULTILINE_PARAMETERS = myAlignDeclarationParameters.isSelected();
settings.ALIGN_MULTILINE_EXTENDS_LIST = myAlignExtendsList.isSelected();
settings.ALIGN_MULTILINE_FOR = myAlignForStatement.isSelected();
}
public void doCollectInformation(ProgressIndicator progress) {
- final boolean firstTime = myFile.getUserData(THE_FIRST_TIME) == null || myEditor.getUserData(THE_FIRST_TIME) == null;
+ final boolean firstTime = isFirstTime(myFile, myEditor, THE_FIRST_TIME);
Runnable runnable = CodeFoldingManager.getInstance(myProject).updateFoldRegionsAsync(myEditor, firstTime);
synchronized (this) {
myRunnable = runnable;
}
}
+ static boolean isFirstTime(PsiFile file, Editor editor, Key<Boolean> key) {
+ return file.getUserData(key) == null || editor.getUserData(key) == null;
+ }
+
+ static void clearFirstTimeFlag(PsiFile file, Editor editor, Key<Boolean> key) {
+ file.putUserData(key, Boolean.FALSE);
+ editor.putUserData(key, Boolean.FALSE);
+ }
+
public void doApplyInformationToEditor() {
Runnable runnable;
synchronized (this) {
try {
runnable.run();
}
- catch (IndexNotReadyException e) {
+ catch (IndexNotReadyException ignored) {
}
}
if (InjectedLanguageUtil.getTopLevelFile(myFile) == myFile) {
- myFile.putUserData(THE_FIRST_TIME, Boolean.FALSE);
- myEditor.putUserData(THE_FIRST_TIME, Boolean.FALSE);
+ clearFirstTimeFlag(myFile, myEditor, THE_FIRST_TIME);
}
}
}
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
class InjectedCodeFoldingPass extends TextEditorHighlightingPass implements DumbAware {
+ private static final Key<Boolean> THE_FIRST_TIME_KEY = Key.create("FirstInjectedFoldingPass");
private Runnable myRunnable;
private final Editor myEditor;
private final PsiFile myFile;
}
public void doCollectInformation(ProgressIndicator progress) {
- Runnable runnable = FoldingUpdate.updateInjectedFoldRegions(myEditor, myFile);
+ boolean firstTime = CodeFoldingPass.isFirstTime(myFile, myEditor, THE_FIRST_TIME_KEY);
+ Runnable runnable = FoldingUpdate.updateInjectedFoldRegions(myEditor, myFile, firstTime);
synchronized (this) {
myRunnable = runnable;
}
try {
runnable.run();
}
- catch (IndexNotReadyException e) {
+ catch (IndexNotReadyException ignored) {
}
+ CodeFoldingPass.clearFirstTimeFlag(myFile, myEditor, THE_FIRST_TIME_KEY);
}
}
}
\ No newline at end of file
final FoldRegion[] regions = editor.getFoldingModel().getAllFoldRegions();
editor.getFoldingModel().runBatchFoldingOperation(new Runnable() {
public void run() {
+ EditorFoldingInfo foldingInfo = EditorFoldingInfo.get(editor);
for (FoldRegion region : regions) {
- PsiElement element = EditorFoldingInfo.get(editor).getPsiElement(region);
+ PsiElement element = foldingInfo.getPsiElement(region);
if (element != null) {
region.setExpanded(!FoldingPolicy.isCollapseByDefault(element));
}
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.FoldRegion;
import com.intellij.openapi.editor.RangeMarker;
-import com.intellij.openapi.editor.impl.FoldRegionImpl;
+import com.intellij.openapi.editor.ex.FoldingModelEx;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.impl.text.CodeFoldingState;
import com.intellij.openapi.project.Project;
FoldRegion region = FoldingUtil.findFoldRegion(editor, marker.getStartOffset(), marker.getEndOffset());
if (region == null) {
String placeHolderText = myPlaceholderTexts.get(marker);
- region = new FoldRegionImpl(editor, marker.getStartOffset(), marker.getEndOffset(), placeHolderText, null); //may fail to add in case intersecting region exists
+ region = ((FoldingModelEx)editor.getFoldingModel()).createFoldRegion(marker.getStartOffset(), marker.getEndOffset(), placeHolderText, null);
+ //may fail to add in case intersecting region exists
if (!editor.getFoldingModel().addFoldRegion(region)) return;
}
package com.intellij.codeInsight.folding.impl;
import com.intellij.injected.editor.DocumentWindow;
+import com.intellij.injected.editor.EditorWindow;
import com.intellij.lang.Language;
import com.intellij.lang.folding.FoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
final TreeMap<PsiElement, FoldingDescriptor> elementsToFoldMap = new TreeMap<PsiElement, FoldingDescriptor>(COMPARE_BY_OFFSET);
getFoldingsFor(file instanceof PsiCompiledElement ? (PsiFile)((PsiCompiledElement)file).getMirror() : file, document, elementsToFoldMap, quick);
- final UpdateFoldRegionsOperation operation =
- new UpdateFoldRegionsOperation(project, editor, elementsToFoldMap, applyDefaultState, false);
+ final UpdateFoldRegionsOperation operation = new UpdateFoldRegionsOperation(project, editor, elementsToFoldMap, applyDefaultState, false);
Runnable runnable = new Runnable() {
public void run() {
editor.getFoldingModel().runBatchFoldingOperationDoNotCollapseCaret(operation);
private static final Key<Object> LAST_UPDATE_INJECTED_STAMP_KEY = Key.create("LAST_UPDATE_INJECTED_STAMP_KEY");
@Nullable
- public static Runnable updateInjectedFoldRegions(@NotNull final Editor editor, @NotNull PsiFile file) {
+ public static Runnable updateInjectedFoldRegions(@NotNull final Editor editor, @NotNull PsiFile file, final boolean applyDefaultState) {
if (file instanceof PsiCompiledElement) return null;
ApplicationManager.getApplication().assertReadAccessAllowed();
Object lastTimeStamp = editor.getUserData(LAST_UPDATE_INJECTED_STAMP_KEY);
if (lastTimeStamp instanceof Long && ((Long)lastTimeStamp).longValue() == timeStamp) return null;
- final TreeMap<PsiElement, FoldingDescriptor> elementsToFoldMap = new TreeMap<PsiElement, FoldingDescriptor>(COMPARE_BY_OFFSET);
-
List<DocumentWindow> injectedDocuments = InjectedLanguageUtil.getCachedInjectedDocuments(file);
if (injectedDocuments.isEmpty()) return null;
+ final List<EditorWindow> injectedEditors = new ArrayList<EditorWindow>();
+ final List<Map<PsiElement, FoldingDescriptor>> maps = new ArrayList<Map<PsiElement, FoldingDescriptor>>();
for (DocumentWindow injectedDocument : injectedDocuments) {
- PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(injectedDocument);
- if (psiFile == null || !psiFile.isValid() || !injectedDocument.isValid()) continue;
- getFoldingsFor(psiFile, injectedDocument, elementsToFoldMap, false);
+ PsiFile injectedFile = PsiDocumentManager.getInstance(project).getPsiFile(injectedDocument);
+ if (injectedFile == null || !injectedFile.isValid() || !injectedDocument.isValid()) continue;
+ Editor injectedEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, injectedFile);
+ if (!(injectedEditor instanceof EditorWindow)) continue;
+
+ injectedEditors.add((EditorWindow)injectedEditor);
+ Map<PsiElement, FoldingDescriptor> map = new TreeMap<PsiElement, FoldingDescriptor>(COMPARE_BY_OFFSET);
+ maps.add(map);
+ getFoldingsFor(injectedFile, injectedDocument, map, false);
}
- final Runnable operation = new UpdateFoldRegionsOperation(project, editor, elementsToFoldMap, false, true);
+
+ final Runnable operation = new Runnable() {
+ public void run() {
+ for (int i = 0; i < injectedEditors.size(); i++) {
+ EditorWindow injectedEditor = injectedEditors.get(i);
+ Map<PsiElement, FoldingDescriptor> map = maps.get(i);
+ new UpdateFoldRegionsOperation(project, injectedEditor, map, applyDefaultState, true).run();
+ }
+ }
+ };
return new Runnable() {
public void run() {
editor.getFoldingModel().runBatchFoldingOperationDoNotCollapseCaret(operation);
};
}
- private static void getFoldingsFor(PsiFile file, Document document, TreeMap<PsiElement, FoldingDescriptor> elementsToFoldMap, boolean quick) {
+ private static void getFoldingsFor(PsiFile file, Document document, Map<PsiElement, FoldingDescriptor> elementsToFoldMap, boolean quick) {
final FileViewProvider viewProvider = file.getViewProvider();
for (final Language language : viewProvider.getLanguages()) {
final PsiFile psi = viewProvider.getPsi(language);