diff --git a/.idea/modules.xml b/.idea/modules.xml index 553b6854a1ac..cb457d298f4a 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -10,6 +10,7 @@ + diff --git a/build/scripts/layouts.gant b/build/scripts/layouts.gant index 1985a382aaa9..734760c5262c 100644 --- a/build/scripts/layouts.gant +++ b/build/scripts/layouts.gant @@ -383,7 +383,10 @@ public def layoutCommunityPlugins(String home) { exclude(name: "**/ddmlib_1.jar") } - jar("android_rt.jar") {module("android-rt")} + jar("android-common.jar") { + module("android-rt") + module("android-common") + } dir("jps") { jar("android-jps-plugin.jar") { module("android-jps-plugin") } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerEditorImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerEditorImpl.java index 5f9eaa4801df..68c6049d4cdc 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerEditorImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerEditorImpl.java @@ -69,13 +69,13 @@ public abstract class DebuggerEditorImpl extends CompletionEditor{ private WeakReference myPopup; private final PsiTreeChangeListener myPsiListener = new PsiTreeChangeAdapter() { - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { checkContext(); } - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { checkContext(); } - public void childMoved(PsiTreeChangeEvent event) { + public void childMoved(@NotNull PsiTreeChangeEvent event) { checkContext(); } private void checkContext() { diff --git a/java/execution/impl/src/com/intellij/execution/junit2/segments/Extractor.java b/java/execution/impl/src/com/intellij/execution/junit2/segments/Extractor.java index 1b087e5ef4d1..de2266aa74dd 100644 --- a/java/execution/impl/src/com/intellij/execution/junit2/segments/Extractor.java +++ b/java/execution/impl/src/com/intellij/execution/junit2/segments/Extractor.java @@ -30,6 +30,7 @@ import org.jetbrains.annotations.NotNull; import java.io.InputStream; import java.io.Reader; import java.nio.charset.Charset; +import java.util.concurrent.atomic.AtomicInteger; /** * @author dyoma @@ -40,7 +41,7 @@ public class Extractor implements Disposable { private OutputPacketProcessor myEventsDispatcher; private static final Logger LOG = Logger.getInstance("#" + Extractor.class.getName()); private final MergingUpdateQueue myQueue = new MergingUpdateQueue("Test Extractor", 20, true, MergingUpdateQueue.ANY_COMPONENT); - private int myOrder = -1; + private AtomicInteger myOrder = new AtomicInteger(-1); public Extractor(@NotNull InputStream stream, @NotNull Charset charset) { myStream = new SegmentedInputStream(stream, charset); @@ -66,7 +67,7 @@ public class Extractor implements Disposable { myFulfilledWorkGate = new DeferredActionsQueue() { //todo make it all later @Override public void addLast(final Runnable runnable) { - myQueue.queue(new MyUpdate(runnable, queue, myOrder++)); + myQueue.queue(new MyUpdate(runnable, queue, myOrder.incrementAndGet())); } @Override 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 a64cc6c8a313..b8a262df7993 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 @@ -33,11 +33,11 @@ public class ConfigFileImpl implements ConfigFile { final VirtualFilePointerManager pointerManager = VirtualFilePointerManager.getInstance(); myFilePointer = pointerManager.create(configuration.getUrl(), this, new VirtualFilePointerListener() { @Override - public void beforeValidityChanged(final VirtualFilePointer[] pointers) { + public void beforeValidityChanged(@NotNull final VirtualFilePointer[] pointers) { } @Override - public void validityChanged(final VirtualFilePointer[] pointers) { + public void validityChanged(@NotNull final VirtualFilePointer[] pointers) { myPsiFile = null; onChange(); } diff --git a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java index 2a9bd85eee2c..258ac5a02d18 100644 --- a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java @@ -576,7 +576,7 @@ public class ExpectedTypesProvider { @Override public void visitPolyadicExpression(PsiPolyadicExpression expr) { PsiExpression[] operands = expr.getOperands(); - int index = Arrays.asList(operands).indexOf(myExpr); + final int index = Arrays.asList(operands).indexOf(myExpr); assert index >= 0; if (myForCompletion && index == 0) { @@ -591,7 +591,7 @@ public class ExpectedTypesProvider { } return; } - PsiExpression anotherExpr = index > 0 ? operands[0] : index < operands.length ? operands[1] : null; + PsiExpression anotherExpr = index > 0 ? operands[0] : 1 < operands.length ? operands[1] : null; PsiType anotherType = anotherExpr != null ? anotherExpr.getType() : null; IElementType i = expr.getOperationTokenType(); if (i == JavaTokenType.MINUS || diff --git a/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java b/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java index 8722fdfd04be..a6790e8bb7e8 100644 --- a/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java +++ b/java/java-impl/src/com/intellij/codeInsight/ExternalAnnotationsManagerImpl.java @@ -65,6 +65,7 @@ import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.util.*; +import com.intellij.util.containers.ConcurrentWeakHashMap; import com.intellij.util.containers.ConcurrentWeakValueHashMap; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.OptionsMessageDialog; @@ -135,9 +136,20 @@ public class ExternalAnnotationsManagerImpl extends ExternalAnnotationsManager { return result.isEmpty() ? null : result.values().toArray(new PsiAnnotation[result.size()]); } + private final Map> cache = new ConcurrentWeakHashMap>(); @NotNull private Map collectExternalAnnotations(@NotNull final PsiModifierListOwner listOwner) { if (hasAnyAnnotationsRoots() == ThreeState.NO) return Collections.emptyMap(); + + Map map = cache.get(listOwner); + if (map == null) { + map = doCollect(listOwner); + cache.put(listOwner, map); + } + return map; + } + + private Map doCollect(@NotNull PsiModifierListOwner listOwner) { final List files = findExternalAnnotationsFiles(listOwner); if (files == null) { return Collections.emptyMap(); @@ -313,10 +325,12 @@ public class ExternalAnnotationsManagerImpl extends ExternalAnnotationsManager { return VfsUtil.toVirtualFileArray(result); } - private void annotateExternally(@NotNull final VirtualFile file, @NotNull final PsiModifierListOwner listOwner, final Project project, + private void annotateExternally(@NotNull final VirtualFile file, + @NotNull final PsiModifierListOwner listOwner, + @NotNull Project project, @NotNull final String packageName, final VirtualFile virtualFile, - final String annotationFQName, + @NotNull final String annotationFQName, @NotNull final PsiFile fromFile, final PsiNameValuePair[] value) { final XmlFile[] annotationsXml = new XmlFile[1]; @@ -352,46 +366,61 @@ public class ExternalAnnotationsManagerImpl extends ExternalAnnotationsManager { @Override public boolean deannotate(@NotNull final PsiModifierListOwner listOwner, @NotNull final String annotationFQN) { - final List files = findExternalAnnotationsFiles(listOwner); - if (files != null) { + try { + final List files = findExternalAnnotationsFiles(listOwner); + if (files == null) { + return false; + } for (XmlFile file : files) { - if (file.isValid()) { - final XmlDocument document = file.getDocument(); - if (document != null) { - final XmlTag rootTag = document.getRootTag(); - if (rootTag != null) { - final String externalName = getExternalName(listOwner, false); - final String oldExternalName = getNormalizedExternalName(listOwner); - for (final XmlTag tag : rootTag.getSubTags()) { - final String className = tag.getAttributeValue("name"); - if (Comparing.strEqual(className, externalName) || Comparing.strEqual(className, oldExternalName)) { - for (XmlTag annotationTag : tag.getSubTags()) { - if (Comparing.strEqual(annotationTag.getAttributeValue("name"), annotationFQN)) { - if (ReadonlyStatusHandler.getInstance(myPsiManager.getProject()) - .ensureFilesWritable(file.getVirtualFile()).hasReadonlyFiles()) { - return false; - } - try { - annotationTag.delete(); - if (tag.getSubTags().length == 0) { - tag.delete(); - } - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - return true; - } - } - return false; - } + if (!file.isValid()) { + continue; + } + final XmlDocument document = file.getDocument(); + if (document == null) { + continue; + } + final XmlTag rootTag = document.getRootTag(); + if (rootTag == null) { + continue; + } + final String externalName = getExternalName(listOwner, false); + final String oldExternalName = getNormalizedExternalName(listOwner); + for (final XmlTag tag : rootTag.getSubTags()) { + final String className = tag.getAttributeValue("name"); + if (!Comparing.strEqual(className, externalName) && !Comparing.strEqual(className, oldExternalName)) { + continue; + } + for (XmlTag annotationTag : tag.getSubTags()) { + if (!Comparing.strEqual(annotationTag.getAttributeValue("name"), annotationFQN)) { + continue; + } + if (ReadonlyStatusHandler.getInstance(myPsiManager.getProject()) + .ensureFilesWritable(file.getVirtualFile()).hasReadonlyFiles()) { + return false; + } + try { + annotationTag.delete(); + if (tag.getSubTags().length == 0) { + tag.delete(); } } + catch (IncorrectOperationException e) { + LOG.error(e); + } + return true; } + return false; } } + return false; } - return false; + finally { + dropCache(); + } + } + + private void dropCache() { + cache.clear(); } @Override @@ -481,11 +510,11 @@ public class ExternalAnnotationsManagerImpl extends ExternalAnnotationsManager { myExternalAnnotations.clear(); } - private void annotateExternally(final PsiModifierListOwner listOwner, - final String annotationFQName, - @Nullable final XmlFile xmlFile, - @NotNull PsiFile codeUsageFile, - PsiNameValuePair[] values) { + private void annotateExternally(@NotNull PsiModifierListOwner listOwner, + @NotNull String annotationFQName, + @Nullable final XmlFile xmlFile, + @NotNull PsiFile codeUsageFile, + PsiNameValuePair[] values) { if (xmlFile == null) return; try { final XmlDocument document = xmlFile.getDocument(); @@ -518,6 +547,7 @@ public class ExternalAnnotationsManagerImpl extends ExternalAnnotationsManager { LOG.error(e); } finally { + dropCache(); if (codeUsageFile.getVirtualFile().isInLocalFileSystem()) { UndoUtil.markPsiFileForUndo(codeUsageFile); } @@ -525,7 +555,8 @@ public class ExternalAnnotationsManagerImpl extends ExternalAnnotationsManager { } @NonNls - private static String createAnnotationTag(String annotationFQName, @Nullable PsiNameValuePair[] values) { + @NotNull + private static String createAnnotationTag(@NotNull String annotationFQName, @Nullable PsiNameValuePair[] values) { @NonNls String text; if (values != null) { text = " \n"; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java index 1f4e18cb3a7e..07d7a31be90d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java @@ -150,7 +150,8 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { final Collection> fieldsToFix = getFieldsToFix(); try { final PsiMethod constructor = constrs.get(0); - final List fields = new ArrayList(); + final LinkedHashSet fields = new LinkedHashSet(); + getFieldsToFix().add(myField); for (SmartPsiElementPointer elementPointer : fieldsToFix) { final PsiField field = elementPointer.getElement(); if (field != null && isAvailable(field) && filterConstructorsIfFieldAlreadyAssigned(new PsiMethod[]{constructor}, field).contains(constructor)) { diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateInnerClassFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateInnerClassFromUsageFix.java index f9a72b4bdebb..a0109f289642 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateInnerClassFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateInnerClassFromUsageFix.java @@ -16,9 +16,6 @@ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.daemon.QuickFixBundle; -import static com.intellij.codeInsight.daemon.impl.quickfix.CreateClassKind.CLASS; -import static com.intellij.codeInsight.daemon.impl.quickfix.CreateClassKind.INTERFACE; - import com.intellij.ide.util.PsiClassListCellRenderer; import com.intellij.ide.util.PsiElementListCellRenderer; import com.intellij.openapi.application.ApplicationManager; @@ -37,6 +34,9 @@ import javax.swing.*; import java.util.ArrayList; import java.util.List; +import static com.intellij.codeInsight.daemon.impl.quickfix.CreateClassKind.CLASS; +import static com.intellij.codeInsight.daemon.impl.quickfix.CreateClassKind.INTERFACE; + /** * @author ven */ @@ -78,7 +78,7 @@ public class CreateInnerClassFromUsageFix extends CreateClassFromUsageBaseFix { PsiMember contextMember = PsiTreeUtil.getParentOfType(run, PsiMember.class); while (contextMember != null) { - if (contextMember instanceof PsiClass) { + if (contextMember instanceof PsiClass && !(contextMember instanceof PsiTypeParameter)) { result.add((PsiClass)contextMember); } run = contextMember; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java index 4952ac69b480..e296214ef7a6 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java @@ -247,6 +247,7 @@ public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix { builder.setEndVariableAfter(body.getLBrace()); accessor = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(accessor); + LOG.assertTrue(accessor != null); targetClass = accessor.getContainingClass(); LOG.assertTrue(targetClass != null); Template template = builder.buildTemplate(); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DelegateWithDefaultParamValueIntentionAction.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DelegateWithDefaultParamValueIntentionAction.java index ea0419f6b474..dc09b28a11e4 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DelegateWithDefaultParamValueIntentionAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/DelegateWithDefaultParamValueIntentionAction.java @@ -30,11 +30,14 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import javax.swing.*; +import java.util.Arrays; +import java.util.HashSet; /** * User: anna @@ -84,7 +87,7 @@ public class DelegateWithDefaultParamValueIntentionAction extends PsiElementBase final PsiParameter parameter = PsiTreeUtil.getParentOfType(element, PsiParameter.class); final PsiMethod method = (PsiMethod)parameter.getDeclarationScope(); final PsiMethod prototype = (PsiMethod)method.getContainingClass().addBefore(generateMethodPrototype(method, parameter), method); - + RefactoringUtil.fixJavadocsForParams(prototype, new HashSet(Arrays.asList(prototype.getParameterList().getParameters()))); TemplateBuilderImpl builder = new TemplateBuilderImpl(prototype); PsiCodeBlock body = prototype.getBody(); diff --git a/java/java-impl/src/com/intellij/codeInspection/accessStaticViaInstance/AccessStaticViaInstance.java b/java/java-impl/src/com/intellij/codeInspection/accessStaticViaInstance/AccessStaticViaInstance.java index fab03cbb389b..5ae5d0c47e1a 100644 --- a/java/java-impl/src/com/intellij/codeInspection/accessStaticViaInstance/AccessStaticViaInstance.java +++ b/java/java-impl/src/com/intellij/codeInspection/accessStaticViaInstance/AccessStaticViaInstance.java @@ -19,6 +19,7 @@ import com.intellij.codeInsight.daemon.JavaErrorMessages; import com.intellij.codeInsight.daemon.impl.analysis.HighlightMessageUtil; import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil; import com.intellij.codeInsight.daemon.impl.quickfix.AccessStaticViaInstanceFix; +import com.intellij.codeInsight.daemon.impl.quickfix.RemoveUnusedVariableFix; import com.intellij.codeInspection.BaseJavaLocalInspectionTool; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.ProblemsHolder; @@ -26,6 +27,8 @@ import com.intellij.psi.*; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; +import java.util.ArrayList; + /** * User: anna * Date: 15-Nov-2005 @@ -87,6 +90,12 @@ public class AccessStaticViaInstance extends BaseJavaLocalInspectionTool { String description = JavaErrorMessages.message("static.member.accessed.via.instance.reference", HighlightUtil.formatType(qualifierExpression.getType()), HighlightMessageUtil.getSymbolName(resolved, result.getSubstitutor())); + if (!onTheFly) { + if (RemoveUnusedVariableFix.checkSideEffects(qualifierExpression, null, new ArrayList())) { + holder.registerProblem(expr, description); + return; + } + } holder.registerProblem(expr, description, new AccessStaticViaInstanceFix(expr, result, onTheFly)); } } diff --git a/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/MethodBodyChecker.java b/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/MethodBodyChecker.java index 1b97ed3a6912..5ee8cadb7ffd 100644 --- a/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/MethodBodyChecker.java +++ b/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/MethodBodyChecker.java @@ -27,12 +27,13 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.UserDataHolderEx; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.reference.SoftReference; import com.intellij.util.IncorrectOperationException; +import com.intellij.util.PatchedSoftReference; import com.intellij.util.containers.ConcurrentHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -75,12 +76,13 @@ public class MethodBodyChecker { } } - private static final Key> CACHE_KEY = new Key>("MethodBodyChecker templates cache"); + private static final Key>> CACHE_KEY = Key.create("MethodBodyChecker templates cache"); private static Map getTemplatesCache(PsiClass aClass) { - Map cache = aClass.getUserData(CACHE_KEY); + SoftReference> ref = aClass.getUserData(CACHE_KEY); + Map cache = ref == null ? null : ref.get(); if (cache == null) { - cache = ((UserDataHolderEx)aClass).putUserDataIfAbsent(CACHE_KEY, new ConcurrentHashMap()); + aClass.putUserData(CACHE_KEY, new PatchedSoftReference>(cache = new ConcurrentHashMap())); } return cache; } diff --git a/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicCompletionContributor.java b/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicCompletionContributor.java index bbee7122b9dc..efc77798a5d0 100644 --- a/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInspection/magicConstant/MagicCompletionContributor.java @@ -174,7 +174,8 @@ public class MagicCompletionContributor extends CompletionContributor { @Override public void consume(CompletionResult completionResult) { LookupElement element = completionResult.getLookupElement(); - if (allowed.contains(element.getObject())) { + Object object = element.getObject(); + if (object instanceof PsiElement && allowed.contains(object)) { return; } result.passResult(completionResult); diff --git a/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java b/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java index 85d27192acb5..5f6072a2bb91 100644 --- a/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java +++ b/java/java-impl/src/com/intellij/refactoring/OptimizeImportsRefactoringHelper.java @@ -104,10 +104,17 @@ public class OptimizeImportsRefactoringHelper implements RefactoringHelper 0) { names = new String[]{StringUtil.join(typeParameters, new Function() { public String fun(PsiType psiType) { + PsiType type = psiType; if (psiType instanceof PsiClassType) { - return ((PsiClassType)psiType).rawType().getPresentableText(); + type = TypeConversionUtil.erasure(psiType); } - return psiType.getPresentableText(); + if (type instanceof PsiArrayType) { + type = type.getDeepComponentType(); + } + return type.getPresentableText(); } }, "") + name, "My" + name}; } else { diff --git a/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java b/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java index c61c5986408e..477369902638 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java @@ -72,6 +72,7 @@ public class ChangeClassSignatureProcessor extends BaseRefactoringProcessor { if (reference.getElement() instanceof PsiJavaCodeReferenceElement) { PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement)reference.getElement(); PsiElement parent = referenceElement.getParent(); + if (parent instanceof PsiTypeElement && parent.getParent() instanceof PsiInstanceOfExpression) continue; if (parent instanceof PsiTypeElement || parent instanceof PsiNewExpression || parent instanceof PsiAnonymousClass || parent instanceof PsiReferenceList) { if (!hadTypeParameters || referenceElement.getTypeParameters().length > 0) { 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 cb8bea661d2e..7f2f57965d61 100644 --- a/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java @@ -298,7 +298,7 @@ public class CopyClassesHandler extends CopyHandlerDelegateBase { @Nullable public static PsiElement doCopyClasses(final Map fileToClasses, - HashMap map, final String copyClassName, + @Nullable HashMap map, final String copyClassName, final PsiDirectory targetDirectory, final Project project) throws IncorrectOperationException { PsiElement newElement = null; @@ -345,8 +345,12 @@ public class CopyClassesHandler extends CopyHandlerDelegateBase { for (PsiFile file : files) { try { - final PsiFile fileCopy = - CopyFilesOrDirectoriesHandler.copyToDirectory(file, getNewFileName(file, copyClassName), targetDirectory, choice); + PsiDirectory finalTarget = targetDirectory; + final String relativePath = map != null ? map.get(file) : null; + if (relativePath != null && !relativePath.isEmpty()) { + finalTarget = buildRelativeDir(targetDirectory, relativePath).findOrCreateTargetDirectory(); + } + final PsiFile fileCopy = CopyFilesOrDirectoriesHandler.copyToDirectory(file, getNewFileName(file, copyClassName), finalTarget, choice); if (fileCopy != null) { createdFiles.add(fileCopy); } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java index abb7d6f18ec8..ac4a41417362 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java @@ -218,9 +218,9 @@ public abstract class BaseExpressionToFieldHandler extends IntroduceHandlerBase return false; } - public static void setModifiers(PsiField field, Settings settings, final boolean declareStatic) { + public static void setModifiers(PsiField field, Settings settings) { if (!settings.isIntroduceEnumConstant()) { - if (declareStatic) { + if (settings.isDeclareStatic()) { PsiUtil.setModifierProperty(field, PsiModifier.STATIC, true); } if (settings.isDeclareFinal()) { @@ -711,7 +711,7 @@ public abstract class BaseExpressionToFieldHandler extends IntroduceHandlerBase createField(myFieldName, myType, initializer, initializerPlace == InitializationPlace.IN_FIELD_DECLARATION && initializer != null, myParentClass); - setModifiers(myField, mySettings, mySettings.isDeclareStatic()); + setModifiers(myField, mySettings); myField = appendField(initializer, initializerPlace, destClass, myParentClass, myAnchorElement, myField); if (!mySettings.isIntroduceEnumConstant()) { VisibilityUtil.fixVisibility(myOccurrences, myField, mySettings.getFieldVisibility()); diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldHandler.java index cfa320ba476c..2abad90e3ef0 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceFieldHandler.java @@ -31,6 +31,8 @@ import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.refactoring.util.occurrences.*; import org.jetbrains.annotations.NotNull; +import java.util.List; + public class IntroduceFieldHandler extends BaseExpressionToFieldHandler { public static final String REFACTORING_NAME = RefactoringBundle.message("introduce.field.title"); @@ -199,10 +201,19 @@ public class IntroduceFieldHandler extends BaseExpressionToFieldHandler { final PsiStatement statement = PsiTreeUtil.getParentOfType(local, PsiStatement.class); return IntroduceFieldHandler.this.showRefactoringDialog(project, editor, aClass, local.getInitializer(), local.getType(), occurences, local, statement); } + + @Override + protected int getChosenClassIndex(List classes) { + return IntroduceFieldHandler.this.getChosenClassIndex(classes); + } }; return localToFieldHandler.convertLocalToField(localVariable, editor); } + protected int getChosenClassIndex(List classes) { + return classes.size() - 1; + } + private static class MyOccurrenceFilter implements OccurrenceFilter { public boolean isOK(PsiExpression occurrence) { return !isInSuperOrThis(occurrence); diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java index 2836d5bb6d50..a991d6e519aa 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java @@ -81,7 +81,7 @@ public abstract class LocalToFieldHandler { if (classes.isEmpty()) return false; if (classes.size() == 1 || ApplicationManager.getApplication().isUnitTestMode()) { - if (convertLocalToField(local, classes.get(classes.size() - 1), editor, tempIsStatic)) return false; + if (convertLocalToField(local, classes.get(getChosenClassIndex(classes)), editor, tempIsStatic)) return false; } else { final boolean isStatic = tempIsStatic; NavigationUtil.getPsiElementPopup(classes.toArray(new PsiClass[classes.size()]), new PsiClassListCellRenderer(), "Choose class to introduce " + (myIsConstant ? "constant" : "field"), new PsiElementProcessor() { @@ -96,6 +96,10 @@ public abstract class LocalToFieldHandler { return true; } + protected int getChosenClassIndex(List classes) { + return classes.size() - 1; + } + private boolean convertLocalToField(PsiLocalVariable local, PsiClass aClass, Editor editor, boolean isStatic) { final PsiExpression[] occurences = CodeInsightUtil.findReferenceExpressions(RefactoringUtil.getVariableScope(local), local); if (editor != null) { @@ -250,7 +254,6 @@ public abstract class LocalToFieldHandler { private final PsiClass myDestinationClass; private final BaseExpressionToFieldHandler.Settings mySettings; private final BaseExpressionToFieldHandler.InitializationPlace myInitializerPlace; - private final boolean myStatic; private final PsiExpression[] myOccurences; private PsiField myField; private PsiStatement myAssignmentStatement; @@ -269,7 +272,6 @@ public abstract class LocalToFieldHandler { myDestinationClass = aClass; mySettings = settings; myInitializerPlace = settings.getInitializerPlace(); - myStatic = isStatic; myOccurences = occurrences; } @@ -288,7 +290,7 @@ public abstract class LocalToFieldHandler { myField = mySettings.isIntroduceEnumConstant() ? EnumConstantsUtil.createEnumConstant(myDestinationClass, myLocal, myFieldName) : createField(myLocal, mySettings.getForcedType(), myFieldName, myInitializerPlace == IN_FIELD_DECLARATION); myField = (PsiField)myDestinationClass.add(myField); - BaseExpressionToFieldHandler.setModifiers(myField, mySettings, myStatic); + BaseExpressionToFieldHandler.setModifiers(myField, mySettings); if (!mySettings.isIntroduceEnumConstant()) { VisibilityUtil.fixVisibility(myOccurences, myField, mySettings.getFieldVisibility()); } diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/AbstractJavaInplaceIntroducer.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/AbstractJavaInplaceIntroducer.java index dd5d6aa995f7..30bfd9c48055 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/AbstractJavaInplaceIntroducer.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/AbstractJavaInplaceIntroducer.java @@ -99,6 +99,7 @@ public abstract class AbstractJavaInplaceIntroducer extends AbstractInplaceIntro @Override protected void saveSettings(@NotNull PsiVariable psiVariable) { TypeSelectorManagerImpl.typeSelected(psiVariable.getType(), getType());//myDefaultType.getType()); + myTypeSelectorManager = null; } public PsiType getType() { diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java index da8f923bd552..95b96eea9818 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java @@ -27,10 +27,7 @@ import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PackageScope; import com.intellij.psi.search.searches.ReferencesSearch; -import com.intellij.psi.util.MethodSignatureUtil; -import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.psi.util.PsiUtil; -import com.intellij.psi.util.PsiUtilBase; +import com.intellij.psi.util.*; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.MoveDestination; import com.intellij.refactoring.PackageWrapper; @@ -68,16 +65,15 @@ public class MoveClassesOrPackagesProcessor extends BaseRefactoringProcessor { private boolean mySearchInNonJavaFiles; private final PackageWrapper myTargetPackage; private final MoveCallback myMoveCallback; - protected final MoveDestination myMoveDestination; + protected @NotNull final MoveDestination myMoveDestination; protected NonCodeUsageInfo[] myNonCodeUsages; - public MoveClassesOrPackagesProcessor( - Project project, - PsiElement[] elements, - final MoveDestination moveDestination, - boolean searchInComments, - boolean searchInNonJavaFiles, - MoveCallback moveCallback) { + public MoveClassesOrPackagesProcessor(Project project, + PsiElement[] elements, + @NotNull final MoveDestination moveDestination, + boolean searchInComments, + boolean searchInNonJavaFiles, + MoveCallback moveCallback) { super(project); final Set toMove = new LinkedHashSet(); for (PsiElement element : elements) { @@ -87,7 +83,7 @@ public class MoveClassesOrPackagesProcessor extends BaseRefactoringProcessor { toMove.add(element); } } - myElementsToMove = PsiUtilBase.toPsiElementArray(toMove); + myElementsToMove = PsiUtilCore.toPsiElementArray(toMove); Arrays.sort(myElementsToMove, new Comparator() { @Override public int compare(PsiElement o1, PsiElement o2) { @@ -451,7 +447,8 @@ public class MoveClassesOrPackagesProcessor extends BaseRefactoringProcessor { if (allClasses.containsKey(psiClass)) { continue; } - final PsiClass[] classes = ((PsiClassOwner)element.getContainingFile()).getClasses(); + final PsiClassOwner containingFile = (PsiClassOwner)element.getContainingFile(); + final PsiClass[] classes = containingFile.getClasses(); boolean all = true; for (PsiClass aClass : classes) { if (ArrayUtil.find(myElementsToMove, aClass) == -1) { @@ -464,14 +461,14 @@ public class MoveClassesOrPackagesProcessor extends BaseRefactoringProcessor { } } } - Map oldToNewElementsMapping = new HashMap(); + final Map oldToNewElementsMapping = new HashMap(); for (int idx = 0; idx < myElementsToMove.length; idx++) { PsiElement element = myElementsToMove[idx]; final RefactoringElementListener elementListener = getTransaction().getElementListener(element); if (element instanceof PsiPackage) { final PsiDirectory[] directories = ((PsiPackage)element).getDirectories(); - final PsiPackage newElement = - MoveClassesOrPackagesUtil.doMovePackage((PsiPackage)element, myMoveDestination); + final PsiPackage newElement = MoveClassesOrPackagesUtil.doMovePackage((PsiPackage)element, myMoveDestination); + LOG.assertTrue(newElement != null); oldToNewElementsMapping.put(element, newElement); int i = 0; final PsiDirectory[] newDirectories = newElement.getDirectories(); 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 b68a98d10d84..cadb5c34b01a 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 @@ -15,7 +15,6 @@ */ package com.intellij.refactoring.move.moveClassesOrPackages; -import com.intellij.ide.util.DirectoryChooser; import com.intellij.ide.util.DirectoryChooserUtil; import com.intellij.lang.java.JavaFindUsagesProvider; import com.intellij.openapi.application.ApplicationManager; @@ -23,7 +22,6 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VfsUtil; @@ -231,6 +229,7 @@ public class MoveClassesOrPackagesUtil { newClass = aClass; if (!moveDestination.equals(file.getContainingDirectory())) { + LOG.assertTrue(file.getVirtualFile() != null, aClass); MoveFilesOrDirectoriesUtil.doMoveFile(file, moveDestination); if (file instanceof PsiClassOwner && newPackage != null) { ((PsiClassOwner)file).setPackageName(newPackage.getQualifiedName()); diff --git a/java/java-impl/src/com/intellij/slicer/SliceManager.java b/java/java-impl/src/com/intellij/slicer/SliceManager.java index 5d79d7c96c22..b853cf37f48d 100644 --- a/java/java-impl/src/com/intellij/slicer/SliceManager.java +++ b/java/java-impl/src/com/intellij/slicer/SliceManager.java @@ -65,32 +65,32 @@ public class SliceManager implements PersistentStateComponent myCalculatedTypes = new ConcurrentWeakHashMap(); - private final ConcurrentMap myCachedReferencesInPsiTypes = new ConcurrentWeakHashMap(); - // e.g. given FileOutputStream os, os2; - // PsiJavaCodeReferenceElement("FileOutputStream") -> [ PsiReferenceExpression("os"), PsiReferenceExpression("os2") ] - private final Map> myCachedReferenceIn_PsiClassReferenceType_To_ListOfReferencesOfThisType_CachedHere = new WeakHashMap>(); + private final ConcurrentMap> myCalculatedTypes = new ConcurrentWeakHashMap>(); private final Map myVarToConstValueMapPhysical; private final Map myVarToConstValueMapNonPhysical; @@ -86,39 +79,31 @@ public class JavaResolveCache { private void clearCaches(boolean isPhysical) { myCalculatedTypes.clear(); - myCachedReferencesInPsiTypes.clear(); - myCachedReferenceIn_PsiClassReferenceType_To_ListOfReferencesOfThisType_CachedHere.clear(); if (isPhysical) { myVarToConstValueMapPhysical.clear(); } myVarToConstValueMapNonPhysical.clear(); } - public boolean isTypeCached(@NotNull PsiExpression expr) { - return myCalculatedTypes.get(expr) != null; - } - @Nullable public PsiType getType(@NotNull T expr, @NotNull Function f) { - PsiType type = myCalculatedTypes.get(expr); + PsiType type = getCachedType(expr); if (type == null) { type = f.fun(expr); if (type == null) { type = TypeConversionUtil.NULL_TYPE; } - PsiType stored = ConcurrencyUtil.cacheOrGet(myCalculatedTypes, expr, type); + SoftReference ref = new SoftReference(type); + Reference storedRef = ConcurrencyUtil.cacheOrGet(myCalculatedTypes, expr, ref); - if (stored == type && DebugUtil.DO_EXPENSIVE_CHECKS) { - registerDiagnosticsHooks(expr, type); - } - - type = stored; + PsiType stored = storedRef.get(); + type = stored == null ? type : stored; } if (!type.isValid()) { if (expr.isValid()) { PsiJavaCodeReferenceElement refInside = type instanceof PsiClassReferenceType ? ((PsiClassReferenceType)type).getReference() : null; - String typeinfo = type + " (" + type.getClass() + ")" + (refInside == null ? "" : "; ref inside: "+refInside + " ("+refInside.getClass()+") valid:"+refInside.isValid()); + @NonNls String typeinfo = type + " (" + type.getClass() + ")" + (refInside == null ? "" : "; ref inside: "+refInside + " ("+refInside.getClass()+") valid:"+refInside.isValid()); LOG.error("Type is invalid: " + typeinfo + "; expr: '" + expr + "' (" + expr.getClass() + ") is valid"); } else { @@ -129,83 +114,9 @@ public class JavaResolveCache { return type == TypeConversionUtil.NULL_TYPE ? null : type; } - private void registerDiagnosticsHooks(T expr, PsiType type) { - if (type instanceof PsiClassReferenceType) { - PsiJavaCodeReferenceElement reference = ((PsiClassReferenceType)type).getReference(); - ConcurrencyUtil.cacheOrGet(myCachedReferencesInPsiTypes, reference, type); - synchronized (myCachedReferenceIn_PsiClassReferenceType_To_ListOfReferencesOfThisType_CachedHere) { - WeakList refsTo = myCachedReferenceIn_PsiClassReferenceType_To_ListOfReferencesOfThisType_CachedHere.get(reference); - if (refsTo==null) { - refsTo = new WeakList(); - myCachedReferenceIn_PsiClassReferenceType_To_ListOfReferencesOfThisType_CachedHere.put(reference, refsTo); - } - refsTo.add(expr); - } - final PsiFile dummyHolder = reference.getContainingFile(); - if (dummyHolder != null && !dummyHolder.isPhysical()) { - PsiElement physicalContext = dummyHolder.getContext(); - PsiFile physicalFile; - if (physicalContext != null && - (physicalFile = physicalContext.getContainingFile()) != null && - physicalFile.getVirtualFile() != null && - !((PsiManagerEx)dummyHolder.getManager()).isAssertOnFileLoading(physicalFile.getVirtualFile())) { - DebugUtil.trackInvalidation(physicalContext, "dummy holder was invalidated", new Processor() { - @Override - public boolean process(PsiElement element) { - DebugUtil.onInvalidated((TreeElement)dummyHolder.getNode()); - return true; - } - }); - } - } - - DebugUtil.trackInvalidation(reference, "Reference inside PsiClassReferenceType was invalidated", new Processor() { - @Override - public boolean process(PsiElement element) { - PsiType cached = myCalculatedTypes.get(element); - if (cached != null) { - LOG.error(element + " (inside ref) is invalid and yet it is still cached: " + cached); - } - PsiType cachedRef = myCachedReferencesInPsiTypes.get(element); - if (cachedRef != null) { - LOG.error(element + " (inside ref) is invalid and yet it is still cached in ref cache: " + cachedRef); - } - - - synchronized (myCachedReferenceIn_PsiClassReferenceType_To_ListOfReferencesOfThisType_CachedHere) { - WeakList refsTo = myCachedReferenceIn_PsiClassReferenceType_To_ListOfReferencesOfThisType_CachedHere.get(element); - if (refsTo != null) { - for (PsiElement ref : refsTo) { - PsiType cachedT = myCalculatedTypes.get(ref); - if (cachedT != null && !cachedT.isValid()) { - LOG.error("During invalidation of " + element + " ("+element.getClass()+")"+ - " cached type " + cachedT + " of the ref "+ref+" ("+ref.getClass()+")"+ - " became invalid and yet it is still cached" - ); - } - } - } - } - - return true; - } - }); - } - DebugUtil.trackInvalidation(expr, "Expression invalidated", new Processor() { - @Override - public boolean process(PsiElement element) { - PsiType cached = myCalculatedTypes.get(element); - if (cached != null) { - LOG.error(element + " is invalid and yet it is still cached: " + cached); - } - - PsiType cachedRef = myCachedReferencesInPsiTypes.get(element); - if (cachedRef != null) { - LOG.error(element + " is invalid and yet it is still cached (inside PsiType): " + cachedRef); - } - return true; - } - }); + private PsiType getCachedType(T expr) { + Reference reference = myCalculatedTypes.get(expr); + return reference == null ? null : reference.get(); } @Nullable diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaElementType.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaElementType.java index 1dd8689c4fd0..69476e9ef24d 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaElementType.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaElementType.java @@ -41,8 +41,7 @@ public interface JavaElementType { private final Constructor myConstructor; private JavaCompositeElementType(@NonNls final String debugName, final Class nodeClass) { - super(debugName); - myConstructor = ReflectionUtil.getDefaultConstructor(nodeClass); + this(debugName, nodeClass, false); } private JavaCompositeElementType(@NonNls final String debugName, final Class nodeClass, final boolean leftBound) { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java index e0e03a36e1d1..561b54560263 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiBinaryExpressionImpl.java @@ -17,7 +17,6 @@ package com.intellij.psi.impl.source.tree.java; import com.intellij.lang.ASTNode; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.JavaResolveCache; import com.intellij.psi.impl.source.tree.ChildRole; @@ -33,6 +32,8 @@ import org.jetbrains.annotations.NotNull; public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements PsiBinaryExpression { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiBinaryExpressionImpl"); + /** used via reflection in {@link com.intellij.psi.impl.source.tree.JavaElementType.JavaCompositeElementType#JavaCompositeElementType(java.lang.String, java.lang.Class)} */ + @SuppressWarnings("UnusedDeclaration") public PsiBinaryExpressionImpl() { this(JavaElementType.BINARY_EXPRESSION); } @@ -79,24 +80,6 @@ public class PsiBinaryExpressionImpl extends ExpressionPsiElement implements Psi PsiType type = TypeConversionUtil.calcTypeForBinaryExpression(null, rType, sign, false); if (type != TypeConversionUtil.NULL_TYPE) return type; - if (lOperand instanceof PsiBinaryExpressionImpl && !JavaResolveCache.getInstance(param.getProject()).isTypeCached(lOperand)) { - // cache all intermediate expression types from bottom up - PsiBinaryExpressionImpl topLevel = param; - PsiElement element = param; - while (element instanceof PsiBinaryExpressionImpl) { - topLevel = (PsiBinaryExpressionImpl)element; - element = element.getParent(); - } - topLevel.accept(new JavaRecursiveElementWalkingVisitor() { - @Override - protected void elementFinished(PsiElement element) { - if (element instanceof PsiExpression) { - ProgressIndicatorProvider.checkCanceled(); - ((PsiExpression)element).getType(); - } - } - }); - } PsiType lType = lOperand.getType(); return TypeConversionUtil.calcTypeForBinaryExpression(lType, rType, sign, true); } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/delegateWithDefaultValue/afterJavadoc.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/delegateWithDefaultValue/afterJavadoc.java new file mode 100644 index 000000000000..8637aaf12ea1 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/delegateWithDefaultValue/afterJavadoc.java @@ -0,0 +1,14 @@ +// "Generate delegated method with default parameter value" "true" +class Test { + /** + */ + void foo() { + foo(); + } + + /** + * @param i + */ + void foo(int ii){ + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/delegateWithDefaultValue/beforeJavadoc.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/delegateWithDefaultValue/beforeJavadoc.java new file mode 100644 index 000000000000..76acc03eb3d5 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/delegateWithDefaultValue/beforeJavadoc.java @@ -0,0 +1,8 @@ +// "Generate delegated method with default parameter value" "true" +class Test { + /** + * @param i + */ + void foo(int ii){ + } +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/changeClassSignature/InstanceOf.java b/java/java-tests/testData/refactoring/changeClassSignature/InstanceOf.java new file mode 100644 index 000000000000..37e7694cf246 --- /dev/null +++ b/java/java-tests/testData/refactoring/changeClassSignature/InstanceOf.java @@ -0,0 +1,11 @@ +public class ChangeClassSignatureAddParameter { + + public void test(Object object) { + if (object instanceof MyClass) { + MyClass myClass = (MyClass)object; + } + } +} + +class MyClass { +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/changeClassSignature/InstanceOf.java.after b/java/java-tests/testData/refactoring/changeClassSignature/InstanceOf.java.after new file mode 100644 index 000000000000..a21b86a3a36b --- /dev/null +++ b/java/java-tests/testData/refactoring/changeClassSignature/InstanceOf.java.after @@ -0,0 +1,11 @@ +public class ChangeClassSignatureAddParameter { + + public void test(Object object) { + if (object instanceof MyClass) { + MyClass myClass = (MyClass)object; + } + } +} + +class MyClass { +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/introduceField/afterStaticFieldInInnerClass.java b/java/java-tests/testData/refactoring/introduceField/afterStaticFieldInInnerClass.java new file mode 100644 index 000000000000..1a3c2aa1d290 --- /dev/null +++ b/java/java-tests/testData/refactoring/introduceField/afterStaticFieldInInnerClass.java @@ -0,0 +1,9 @@ +public class A { + private static final class Inner { + public final String string; + + public Inner(Integer param) { + string = param.toString(); + } + } +} diff --git a/java/java-tests/testData/refactoring/introduceField/beforeStaticFieldInInnerClass.java b/java/java-tests/testData/refactoring/introduceField/beforeStaticFieldInInnerClass.java new file mode 100644 index 000000000000..3e1b9ef7b00b --- /dev/null +++ b/java/java-tests/testData/refactoring/introduceField/beforeStaticFieldInInnerClass.java @@ -0,0 +1,7 @@ +public class A { + private static final class Inner { + public Inner(Integer param) { + String str = param.toString(); + } + } +} diff --git a/java/java-tests/testData/refactoring/migration/packageToNonExistentPackage/after/p1/C1.java b/java/java-tests/testData/refactoring/migration/packageToNonExistentPackage/after/p1/C1.java index dd6403feaa2d..bd90b5874462 100644 --- a/java/java-tests/testData/refactoring/migration/packageToNonExistentPackage/after/p1/C1.java +++ b/java/java-tests/testData/refactoring/migration/packageToNonExistentPackage/after/p1/C1.java @@ -1,5 +1,7 @@ package p1; +import zzz.bbb.*; + class C { zzz.bbb.AAA a = new zzz.bbb.AAA(); } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/AddAnnotationFixTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/AddAnnotationFixTest.java index b9f60b8b4544..a227292ceaae 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/AddAnnotationFixTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/AddAnnotationFixTest.java @@ -45,7 +45,7 @@ public class AddAnnotationFixTest extends UsefulTestCase { @Override public void setUp() throws Exception { super.setUp(); - final TestFixtureBuilder projectBuilder = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(); + final TestFixtureBuilder projectBuilder = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getName()); myFixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(projectBuilder.getFixture()); final String dataPath = PathManagerEx.getTestDataPath() + "/codeInsight/externalAnnotations"; diff --git a/java/java-tests/testSrc/com/intellij/psi/AstLeaksTest.groovy b/java/java-tests/testSrc/com/intellij/psi/AstLeaksTest.groovy index c8524fc0a346..eafeaf0e3897 100644 --- a/java/java-tests/testSrc/com/intellij/psi/AstLeaksTest.groovy +++ b/java/java-tests/testSrc/com/intellij/psi/AstLeaksTest.groovy @@ -22,6 +22,7 @@ import com.intellij.psi.impl.source.tree.java.MethodElement import com.intellij.testFramework.LeakHunter import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import com.intellij.util.Processor +import com.intellij.codeInspection.defaultFileTemplateUsage.DefaultFileTemplateUsageInspection /** * @author peter @@ -74,4 +75,14 @@ class AstLeaksTest extends LightCodeInsightFixtureTestCase { LeakHunter.checkLeak(sup, MethodElement) } + public void "test no hard refs to Default File Template inspection internal AST"() { + myFixture.addFileToProject('sup.java', 'class Super { void bar() {} }') + PsiJavaFile foo = myFixture.addFileToProject('a.java', 'class Foo { void bar() { bar(); } }') + myFixture.configureFromExistingVirtualFile(foo.virtualFile) + myFixture.enableInspections(new DefaultFileTemplateUsageInspection()) + myFixture.doHighlighting() + + LeakHunter.checkLeak(foo.classes[0], MethodElement, { MethodElement node -> !node.psi.physical } as Processor) + } + } diff --git a/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy b/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy index 3ad83a0f32bd..33e03333c8b7 100644 --- a/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy +++ b/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy @@ -35,11 +35,11 @@ class StubAstSwitchTest extends LightCodeInsightFixtureTestCase { def oldCount = psiManager.modificationTracker.javaStructureModificationCount ApplicationManager.application.runWriteAction { file.virtualFile.setBinaryContent(file.virtualFile.contentsToByteArray()) } - assert file.stub assert psiManager.modificationTracker.javaStructureModificationCount != oldCount assert !cls.valid + assert file.stub assert cls != PsiTreeUtil.findElementOfClassAtOffset(file, 1, PsiClass, false) assert !file.stub } diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/EventsTestListener.java b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/EventsTestListener.java index c8dfde3442c1..77a84f08ce6b 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/EventsTestListener.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/EventsTestListener.java @@ -2,6 +2,7 @@ package com.intellij.psi.impl.file.impl; import com.intellij.psi.PsiTreeChangeEvent; import com.intellij.psi.PsiTreeChangeListener; +import org.jetbrains.annotations.NotNull; /** * @author dsl @@ -14,62 +15,62 @@ class EventsTestListener implements PsiTreeChangeListener { } @Override - public void beforeChildAddition(PsiTreeChangeEvent event) { + public void beforeChildAddition(@NotNull PsiTreeChangeEvent event) { myBuffer.append("beforeChildAddition\n"); } @Override - public void beforeChildRemoval(PsiTreeChangeEvent event) { + public void beforeChildRemoval(@NotNull PsiTreeChangeEvent event) { myBuffer.append("beforeChildRemoval\n"); } @Override - public void beforeChildReplacement(PsiTreeChangeEvent event) { + public void beforeChildReplacement(@NotNull PsiTreeChangeEvent event) { myBuffer.append("beforeChildReplacement\n"); } @Override - public void beforeChildMovement(PsiTreeChangeEvent event) { + public void beforeChildMovement(@NotNull PsiTreeChangeEvent event) { myBuffer.append("beforeChildMovement\n"); } @Override - public void beforeChildrenChange(PsiTreeChangeEvent event) { + public void beforeChildrenChange(@NotNull PsiTreeChangeEvent event) { myBuffer.append("beforeChildrenChange\n"); } @Override - public void beforePropertyChange(PsiTreeChangeEvent event) { + public void beforePropertyChange(@NotNull PsiTreeChangeEvent event) { myBuffer.append("beforePropertyChange\n"); } @Override - public void childAdded(PsiTreeChangeEvent event) { + public void childAdded(@NotNull PsiTreeChangeEvent event) { myBuffer.append("childAdded\n"); } @Override - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { myBuffer.append("childRemoved\n"); } @Override - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { myBuffer.append("childReplaced\n"); } @Override - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { myBuffer.append("childrenChanged\n"); } @Override - public void childMoved(PsiTreeChangeEvent event) { + public void childMoved(@NotNull PsiTreeChangeEvent event) { myBuffer.append("childMoved\n"); } @Override - public void propertyChanged(PsiTreeChangeEvent event) { + public void propertyChanged(@NotNull PsiTreeChangeEvent event) { myBuffer.append("propertyChanged\n"); } } diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/InvalidateClassFileTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/InvalidateClassFileTest.java index 721f0d4dd3cc..7985135211d4 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/InvalidateClassFileTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/InvalidateClassFileTest.java @@ -31,6 +31,7 @@ import com.intellij.psi.PsiTreeChangeAdapter; import com.intellij.psi.PsiTreeChangeEvent; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testFramework.PsiTestCase; +import org.jetbrains.annotations.NotNull; import java.io.File; @@ -78,12 +79,12 @@ public class InvalidateClassFileTest extends PsiTestCase { final boolean[] notified = new boolean[] {false}; final PsiTreeChangeAdapter listener = new PsiTreeChangeAdapter() { @Override - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { notified[0] = true; } @Override - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { notified[0] = true; } }; diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/PsiEventsTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/PsiEventsTest.java index 884e0388d0a5..c0ee2cde55e5 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/PsiEventsTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/PsiEventsTest.java @@ -21,6 +21,7 @@ import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testFramework.PsiTestCase; import com.intellij.util.io.ReadOnlyAttributeUtil; import com.intellij.util.WaitFor; +import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; @@ -529,7 +530,7 @@ public class PsiEventsTest extends PsiTestCase { final VirtualFile virtualFile = createFile("a.xml", "").getVirtualFile(); final PsiTreeChangeAdapter listener = new PsiTreeChangeAdapter() { @Override - public void propertyChanged(PsiTreeChangeEvent event) { + public void propertyChanged(@NotNull PsiTreeChangeEvent event) { getJavaFacade().findClass("XXX", GlobalSearchScope.allScope(myProject)); } }; @@ -544,67 +545,67 @@ public class PsiEventsTest extends PsiTestCase { public void testBeforeAfterChildrenChange() throws Throwable { listener = new PsiTreeChangeListener() { @Override - public void beforeChildAddition(PsiTreeChangeEvent event) { + public void beforeChildAddition(@NotNull PsiTreeChangeEvent event) { logEvent(event); } @Override - public void beforeChildRemoval(PsiTreeChangeEvent event) { + public void beforeChildRemoval(@NotNull PsiTreeChangeEvent event) { logEvent(event); } @Override - public void beforeChildReplacement(PsiTreeChangeEvent event) { + public void beforeChildReplacement(@NotNull PsiTreeChangeEvent event) { logEvent(event); } @Override - public void beforeChildMovement(PsiTreeChangeEvent event) { + public void beforeChildMovement(@NotNull PsiTreeChangeEvent event) { logEvent(event); } @Override - public void beforeChildrenChange(PsiTreeChangeEvent event) { + public void beforeChildrenChange(@NotNull PsiTreeChangeEvent event) { logEvent(event); } @Override - public void beforePropertyChange(PsiTreeChangeEvent event) { + public void beforePropertyChange(@NotNull PsiTreeChangeEvent event) { logEvent(event); } @Override - public void childAdded(PsiTreeChangeEvent event) { + public void childAdded(@NotNull PsiTreeChangeEvent event) { logEvent(event); assertBeforeEventFired(event); } @Override - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { logEvent(event); assertBeforeEventFired(event); } @Override - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { logEvent(event); assertBeforeEventFired(event); } @Override - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { logEvent(event); assertBeforeEventFired(event); } @Override - public void childMoved(PsiTreeChangeEvent event) { + public void childMoved(@NotNull PsiTreeChangeEvent event) { logEvent(event); assertBeforeEventFired(event); } @Override - public void propertyChanged(PsiTreeChangeEvent event) { + public void propertyChanged(@NotNull PsiTreeChangeEvent event) { logEvent(event); assertBeforeEventFired(event); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceFieldInSameClassTest.java b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceFieldInSameClassTest.java index 28a6c6ce2c83..c394c2d353d0 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceFieldInSameClassTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceFieldInSameClassTest.java @@ -1,12 +1,15 @@ package com.intellij.refactoring; import com.intellij.JavaTestUtil; +import com.intellij.psi.PsiClass; import com.intellij.psi.PsiPrimitiveType; import com.intellij.psi.PsiType; import com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.testFramework.LightCodeInsightTestCase; +import java.util.List; + /** * @author ven */ @@ -115,4 +118,16 @@ public class IntroduceFieldInSameClassTest extends LightCodeInsightTestCase { performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false); checkResultByFile("/refactoring/introduceField/afterLocalVarAnnotations.java"); } + + public void testStaticFieldInInnerClass() throws Exception { + configureByFile("/refactoring/introduceField/beforeStaticFieldInInnerClass.java"); + new MockIntroduceFieldHandler(BaseExpressionToFieldHandler.InitializationPlace.IN_CURRENT_METHOD, false){ + @Override + protected int getChosenClassIndex(List classes) { + return 0; + } + }.invoke(getProject(), myEditor, myFile, null); + checkResultByFile("/refactoring/introduceField/afterStaticFieldInInnerClass.java"); + } + } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureTest.java b/java/java-tests/testSrc/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureTest.java index c05b237a6c01..711119964849 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureTest.java @@ -30,6 +30,17 @@ public class ChangeClassSignatureTest extends LightRefactoringTestCase { }); } + public void testInstanceOf() throws Exception { + doTest(new GenParams() { + @Override + public TypeParameterInfo[] gen(PsiClass aClass) throws IncorrectOperationException { + return new TypeParameterInfo[]{ + new TypeParameterInfo(aClass, "T", "java.lang.String") + }; + } + }); + } + public void testSubstituteParamInsideClass() throws Exception { doTest(new GenParams() { @Override diff --git a/java/openapi/src/com/intellij/execution/filters/ExceptionWorker.java b/java/openapi/src/com/intellij/execution/filters/ExceptionWorker.java index 4c80ff258045..8644641dfc96 100644 --- a/java/openapi/src/com/intellij/execution/filters/ExceptionWorker.java +++ b/java/openapi/src/com/intellij/execution/filters/ExceptionWorker.java @@ -30,6 +30,7 @@ import com.intellij.psi.PsiManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiShortNamesCache; import com.intellij.util.ui.UIUtil; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import java.awt.*; @@ -40,6 +41,9 @@ import java.awt.*; * Time: 8:36 PM */ public class ExceptionWorker { + @NonNls private static final String AT = "at"; + private static final String AT_PREFIX = AT + " "; + private static final String STANDALONE_AT = " " + AT + " "; private static final TextAttributes HYPERLINK_ATTRIBUTES = EditorColorsManager .getInstance().getGlobalScheme().getAttributes(CodeInsightColors.HYPERLINK_ATTRIBUTES); @@ -73,12 +77,12 @@ public class ExceptionWorker { final int lparenthIndex = myInfo.third.getStartOffset(); final int rparenthIndex = myInfo.third.getEndOffset(); - final String fileAndLine = line.substring(lparenthIndex + 1, rparenthIndex); + final String fileAndLine = line.substring(lparenthIndex + 1, rparenthIndex).trim(); final int colonIndex = fileAndLine.lastIndexOf(':'); - if (colonIndex <= 0) return; + if (colonIndex < 0) return; - final String lineString = fileAndLine.substring(colonIndex + 1).trim(); + final String lineString = fileAndLine.substring(colonIndex + 1); try { final int lineNumber = Integer.parseInt(lineString); final PsiManager manager = PsiManager.getInstance(myProject); @@ -142,18 +146,34 @@ public class ExceptionWorker { return myInfo; } + //todo [roma] regexp @Nullable static Trinity parseExceptionLine(final String line) { - int lparenIdx = line.indexOf('('); - int rparenIdx = line.indexOf(')', lparenIdx + 1); - if (lparenIdx < 0 || rparenIdx <= lparenIdx) return null; + int startIdx; + if (line.startsWith(AT_PREFIX)){ + startIdx = 0; + } + else{ + startIdx = line.indexOf(STANDALONE_AT); + if (startIdx < 0) { + startIdx = line.indexOf(AT_PREFIX); + } - int dotIdx = line.lastIndexOf('.', lparenIdx); - int startIdx = handleSpaces(line, dotIdx, -1, false); - if (startIdx == dotIdx) return null; + if (startIdx < 0) { + startIdx = -1; + } + } + + final int lparenIdx = line.indexOf('(', startIdx); + if (lparenIdx < 0) return null; + final int dotIdx = line.lastIndexOf('.', lparenIdx); + if (dotIdx < 0 || dotIdx < startIdx) return null; + + final int rparenIdx = line.indexOf(')', lparenIdx); + if (rparenIdx < 0) return null; // class, method, link - return Trinity.create(new TextRange(startIdx + 1, handleSpaces(line, dotIdx, -1, true)), + return Trinity.create(new TextRange(startIdx + 1 + (startIdx >= 0 ? AT.length() : 0), handleSpaces(line, dotIdx, -1, true)), new TextRange(handleSpaces(line, dotIdx + 1, 1, true), handleSpaces(line, lparenIdx + 1, -1, true)), new TextRange(lparenIdx, rparenIdx)); } diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java index 4e7eccf3a2e9..5d1d585234df 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java @@ -87,7 +87,15 @@ public class IncProjectBuilder { CompileContext context = null; try { try { - context = createContext(scope, isMake, isProjectRebuild); + if (myProjectDescriptor.dataManager.versionDiffers()) { + myMessageDispatcher.processMessage(new CompilerMessage( + COMPILE_SERVER_NAME, BuildMessage.Kind.INFO, "Dependency data format has changed, project rebuild required" + )); + context = createContextForForcedRebuild(scope, isMake, isProjectRebuild); + } + else { + context = createContext(scope, isMake, isProjectRebuild); + } runBuild(context); } catch (ProjectBuildException e) { @@ -100,20 +108,14 @@ public class IncProjectBuilder { e.getMessage()) ); flushContext(context); - if (isMake || isProjectRebuild) { - context = createContext(new AllProjectScope(scope.getProject(), scope.getArtifacts(), true), false, true); - } - else { - //in case of forced compilation keep the scope, but remove all caches - context = createContext(scope, false, false); - cleanOutputRoots(context); - } + context = createContextForForcedRebuild(scope, isMake, isProjectRebuild); runBuild(context); } else { throw e; } } + myProjectDescriptor.dataManager.saveVersion(); } catch (ProjectBuildException e) { final Throwable cause = e.getCause(); @@ -133,6 +135,19 @@ public class IncProjectBuilder { } } + private CompileContext createContextForForcedRebuild(CompileScope scope, boolean isMake, boolean isProjectRebuild) throws ProjectBuildException { + final CompileContext context; + if (isMake || isProjectRebuild) { + context = createContext(new AllProjectScope(scope.getProject(), scope.getArtifacts(), true), false, true); + } + else { + //in case of forced compilation keep the scope, but remove all caches + context = createContext(scope, false, false); + cleanOutputRoots(context); + } + return context; + } + private static void flushContext(CompileContext context) { if (context != null) { context.getTimestampStorage().force(); diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java index 93a545acd405..af688e5ba83e 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java @@ -8,8 +8,7 @@ import org.jetbrains.jps.Module; import org.jetbrains.jps.ModuleChunk; import org.jetbrains.jps.incremental.artifacts.ArtifactsBuildData; -import java.io.File; -import java.io.IOException; +import java.io.*; import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -19,6 +18,7 @@ import java.util.Map; * Date: 10/7/11 */ public class BuildDataManager { + private static final int VERSION = 1; private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.storage.BuildDataManager"); private static final String SRC_TO_OUTPUTS_STORAGE = "src-out"; private static final String SRC_TO_FORM_STORAGE = "src-form"; @@ -32,12 +32,14 @@ public class BuildDataManager { private final ArtifactsBuildData myArtifactsBuildData; private final Mappings myMappings; private final File myDataStorageRoot; + private final File myVersionFile; public BuildDataManager(final File dataStorageRoot, final boolean useMemoryTempCaches) throws IOException { myDataStorageRoot = dataStorageRoot; mySrcToFormMap = new SourceToFormMapping(new File(getSourceToFormsRoot(), "data")); myMappings = new Mappings(getMappingsRoot(), useMemoryTempCaches); myArtifactsBuildData = new ArtifactsBuildData(new File(dataStorageRoot, "artifacts")); + myVersionFile = new File(myDataStorageRoot, "version.dat"); } public SourceToOutputMapping getSourceToOutputMap(String moduleName, boolean testSources) throws IOException { @@ -237,4 +239,50 @@ public class BuildDataManager { } } } + + private Boolean myVersionDiffers = null; + + public boolean versionDiffers() { + final Boolean cached = myVersionDiffers; + if (cached != null) { + return cached; + } + try { + final DataInputStream is = new DataInputStream(new FileInputStream(myVersionFile)); + try { + final boolean diff = is.readInt() != VERSION; + myVersionDiffers = diff; + return diff; + } + finally { + is.close(); + } + } + catch (FileNotFoundException ignored) { + return false; // treat it as a new dir + } + catch (IOException ex) { + LOG.info(ex); + } + return true; + } + + public void saveVersion() { + final Boolean differs = myVersionDiffers; + if (differs == null || differs) { + try { + FileUtil.createIfDoesntExist(myVersionFile); + final DataOutputStream os = new DataOutputStream(new FileOutputStream(myVersionFile)); + try { + os.writeInt(VERSION); + myVersionDiffers = Boolean.FALSE; + } + finally { + os.close(); + } + } + catch (IOException ignored) { + } + } + } } diff --git a/jps/jps-builders/src/org/jetbrains/jps/server/ClasspathBootstrap.java b/jps/jps-builders/src/org/jetbrains/jps/server/ClasspathBootstrap.java index ffc4b7efff97..be4dec0b646a 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/server/ClasspathBootstrap.java +++ b/jps/jps-builders/src/org/jetbrains/jps/server/ClasspathBootstrap.java @@ -15,29 +15,24 @@ */ package org.jetbrains.jps.server; -import com.google.common.cache.CacheBuilder; +import com.google.protobuf.Message; import com.intellij.compiler.notNullVerification.NotNullVerifyingInstrumenter; import com.intellij.openapi.application.PathManager; -import com.intellij.openapi.util.io.FileUtil; import com.intellij.uiDesigner.compiler.AlienFormFileException; import com.intellij.uiDesigner.core.GridConstraints; import com.jgoodies.forms.layout.CellConstraints; -import com.sun.jna.Pointer; -import gnu.trove.TIntHash; import net.n3.nanoxml.IXMLBuilder; import org.codehaus.groovy.GroovyException; +import org.jboss.netty.util.Version; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.MacroExpander; import org.jetbrains.jps.javac.JavacServer; -import com.intellij.openapi.util.io.FileUtilRt; import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.commons.EmptyVisitor; import javax.tools.*; import java.io.File; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; +import java.util.*; /** * @author Eugene Zhuravlev @@ -88,24 +83,18 @@ public class ClasspathBootstrap { public static List getCompileServerApplicationClasspath() { final Set cp = new LinkedHashSet(); cp.add(getResourcePath(Server.class)); - cp.add(getResourcePath(com.google.protobuf.Message.class)); // protobuf - cp.add(getResourcePath(org.jboss.netty.bootstrap.Bootstrap.class)); // netty - cp.add(getResourcePath(TIntHash.class)); // trove - cp.add(getResourcePath(FileUtilRt.class)); // util-rt module - cp.add(getResourcePath(FileUtil.class)); // util module - cp.add(getResourcePath(Pointer.class)); // jna.jar - cp.add(getResourcePath(CacheBuilder.class)); // guava + for (String path : PathManager.getUtilClassPath()) { cp.add(new File(path)); } // util + cp.add(getResourcePath(Message.class)); // protobuf + cp.add(getResourcePath(Version.class)); // netty cp.add(getResourcePath(ClassWriter.class)); // asm - cp.add(getResourcePath(org.objectweb.asm.commons.EmptyVisitor.class)); // asm-commons + cp.add(getResourcePath(EmptyVisitor.class)); // asm-commons cp.add(getResourcePath(MacroExpander.class)); // jps-model cp.add(getResourcePath(AlienFormFileException.class)); // forms-compiler cp.add(getResourcePath(GroovyException.class)); // groovy - cp.add(getResourcePath(org.jdom.input.SAXBuilder.class)); // jdom cp.add(getResourcePath(GridConstraints.class)); // forms-rt cp.add(getResourcePath(CellConstraints.class)); // jgoodies-forms cp.add(getResourcePath(NotNullVerifyingInstrumenter.class)); // not-null cp.add(getResourcePath(IXMLBuilder.class)); // nano-xml - cp.add(getResourcePath(org.apache.log4j.Logger.class)); // log4j final Class optimizedFileManagerClass = getOptimizedFileManagerClass(); if (optimizedFileManagerClass != null) { @@ -133,14 +122,9 @@ public class ClasspathBootstrap { public static List getJavacServerClasspath() { final Set cp = new LinkedHashSet(); cp.add(getResourcePath(JavacServer.class)); - cp.add(getResourcePath(com.google.protobuf.Message.class)); // protobuf - cp.add(getResourcePath(org.jboss.netty.bootstrap.Bootstrap.class)); // netty - cp.add(getResourcePath(TIntHash.class)); // trove - cp.add(getResourcePath(FileUtilRt.class)); // util-rt module - cp.add(getResourcePath(FileUtil.class)); // util module - cp.add(getResourcePath(Pointer.class)); // jna.jar - cp.add(getResourcePath(CacheBuilder.class)); // guava - cp.add(getResourcePath(org.jdom.input.SAXBuilder.class)); // jdom + for (String path : PathManager.getUtilClassPath()) { cp.add(new File(path)); } // util + cp.add(getResourcePath(Message.class)); // protobuf + cp.add(getResourcePath(Version.class)); // netty final Class optimizedFileManagerClass = getOptimizedFileManagerClass(); if (optimizedFileManagerClass != null) { @@ -178,5 +162,4 @@ public class ClasspathBootstrap { public static File getResourcePath(Class aClass) { return new File(PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class")); } - } diff --git a/jps/jps-builders/src/org/jetbrains/jps/server/Server.java b/jps/jps-builders/src/org/jetbrains/jps/server/Server.java index 937a4cd393b4..42c1141bcda3 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/server/Server.java +++ b/jps/jps-builders/src/org/jetbrains/jps/server/Server.java @@ -130,12 +130,15 @@ public class Server { } private void doStop(long elapsedTime) { - try { - System.out.println("Stopping compile server; reason: no pings from client received in " + elapsedTime + " ms"); - myMessageHandler.cancelAllBuildsAndClearState(); - } - finally { - stop(); + if (!myMessageHandler.hasRunningBuilds()) { + try { + System.out.println("Stopping compile server; reason: no pings from client received in " + elapsedTime + " ms"); + myMessageHandler.cancelAllBuildsAndClearState(); + stop(); + } + finally { + System.exit(0); + } } } }, allowedIdlePeriod, allowedIdlePeriod, TimeUnit.MILLISECONDS); diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/Mappings.java b/jps/model/src/org/jetbrains/ether/dependencyView/Mappings.java index 7ff64fdb13bc..6af8cfc58e9d 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/Mappings.java +++ b/jps/model/src/org/jetbrains/ether/dependencyView/Mappings.java @@ -1070,10 +1070,12 @@ public class Mappings { } else { + final Option inheritorOf = self.isInheritorOf(cc.name, it.name); + debug("Method: ", mm.name); debug("Class : ", cc.name); - if (overrides.satisfy(mm)) { + if (overrides.satisfy(mm) && inheritorOf.isValue() && inheritorOf.value()) { debug("Current method overrides that found"); final Option subtypeOf = u.isSubtypeOf(mm.type, m.type); @@ -1099,8 +1101,6 @@ public class Mappings { final Collection yetPropagated = self.propagateMethodAccess(mm.name, it.name); - final Option inheritorOf = self.isInheritorOf(cc.name, it.name); - if (inheritorOf.isValue() && inheritorOf.value()) { final Collection deps = myClassToClassDependency.get(cc.name); diff --git a/platform/core-api/src/com/intellij/psi/PsiTreeChangeListener.java b/platform/core-api/src/com/intellij/psi/PsiTreeChangeListener.java index 13bf56366928..f08f2335cfd6 100644 --- a/platform/core-api/src/com/intellij/psi/PsiTreeChangeListener.java +++ b/platform/core-api/src/com/intellij/psi/PsiTreeChangeListener.java @@ -15,6 +15,8 @@ */ package com.intellij.psi; +import org.jetbrains.annotations.NotNull; + import java.util.EventListener; /** @@ -31,7 +33,7 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void beforeChildAddition(PsiTreeChangeEvent event); + void beforeChildAddition(@NotNull PsiTreeChangeEvent event); /** * Invoked just before removal of a child from the tree.
@@ -40,7 +42,7 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void beforeChildRemoval(PsiTreeChangeEvent event); + void beforeChildRemoval(@NotNull PsiTreeChangeEvent event); /** * Invoked just before replacement of a child in the tree by another element.
@@ -49,7 +51,7 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void beforeChildReplacement(PsiTreeChangeEvent event); + void beforeChildReplacement(@NotNull PsiTreeChangeEvent event); /** * Invoked just before movement of a child in the tree by changing its parent or by changing its position in the same parent.
@@ -59,7 +61,7 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void beforeChildMovement(PsiTreeChangeEvent event); + void beforeChildMovement(@NotNull PsiTreeChangeEvent event); /** * Invoked before a mass change of children of the specified node.
@@ -67,7 +69,7 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void beforeChildrenChange(PsiTreeChangeEvent event); + void beforeChildrenChange(@NotNull PsiTreeChangeEvent event); /** * Invoked just before changing of some property of an element.
@@ -77,7 +79,7 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void beforePropertyChange(PsiTreeChangeEvent event); + void beforePropertyChange(@NotNull PsiTreeChangeEvent event); /** * Invoked just after adding of a new child to the tree.
@@ -86,7 +88,7 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void childAdded(PsiTreeChangeEvent event); + void childAdded(@NotNull PsiTreeChangeEvent event); /** * Invoked just after removal of a child from the tree.
@@ -97,7 +99,7 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void childRemoved(PsiTreeChangeEvent event); + void childRemoved(@NotNull PsiTreeChangeEvent event); /** * Invoked just after replacement of a child in the tree by another element.
@@ -109,7 +111,7 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void childReplaced(PsiTreeChangeEvent event); + void childReplaced(@NotNull PsiTreeChangeEvent event); /** * Invoked after a mass change of children of the specified node.
@@ -117,7 +119,7 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void childrenChanged(PsiTreeChangeEvent event); + void childrenChanged(@NotNull PsiTreeChangeEvent event); /** * Invoked just after movement of a child in the tree by changing its parent or by changing its position in the same parent.
@@ -127,7 +129,7 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void childMoved(PsiTreeChangeEvent event); + void childMoved(@NotNull PsiTreeChangeEvent event); /** * Invoked just after changing of some property of an element.
@@ -138,5 +140,5 @@ public interface PsiTreeChangeListener extends EventListener { * * @param event the event object describing the change. */ - void propertyChanged(PsiTreeChangeEvent event); + void propertyChanged(@NotNull PsiTreeChangeEvent event); } diff --git a/platform/core-impl/src/com/intellij/openapi/editor/impl/IntervalTreeImpl.java b/platform/core-impl/src/com/intellij/openapi/editor/impl/IntervalTreeImpl.java index d288d7cbe9a6..54ab504d2a94 100644 --- a/platform/core-impl/src/com/intellij/openapi/editor/impl/IntervalTreeImpl.java +++ b/platform/core-impl/src/com/intellij/openapi/editor/impl/IntervalTreeImpl.java @@ -58,6 +58,11 @@ public abstract class IntervalTreeImpl extends RedBla protected int delta; // delta of startOffset. getStartOffset() = myStartOffset + Sum of deltas up to root private volatile long cachedDeltaUpToRoot; // field (packed to long for atomicity) containing deltaUpToRoot, node modCount and allDeltasUpAreNull flag + // fields are packed as following + // private int modCount; // if it equals to the com.intellij.openapi.editor.impl.RedBlackTree.modCount then deltaUpToRoot can be used, otherwise it is expired + // private int deltaUpToRoot; // sum of all deltas up to the root (including this node' delta). Has valid value only if modCount == IntervalTreeImpl.this.modCount + // private boolean allDeltasUpAreNull; // true if all deltas up the tree (including this node) are 0. Has valid value only if modCount == IntervalTreeImpl.this.modCount + private final IntervalTreeImpl myIntervalTree; public IntervalNode(IntervalTreeImpl intervalTree, @NotNull E key, int start, int end) { @@ -167,16 +172,13 @@ public abstract class IntervalTreeImpl extends RedBla } protected int computeDeltaUpToRoot() { - return computeDeltaUpToRoot(new NodeCachedOffsets()); - } - protected int computeDeltaUpToRoot(NodeCachedOffsets cached) { restart: while (true) { // have to restart on failure to update cached offsets in case of concurrent modification if (!isValid()) return 0; int treeModCount = myIntervalTree.modCount; - unpackCachedValuesTo(cached); - if (cached.modCount == treeModCount) { - return cached.deltaUpToRoot; + long packedOffsets = cachedDeltaUpToRoot; + if (modCount(packedOffsets) == treeModCount) { + return deltaUpToRoot(packedOffsets); } try { myIntervalTree.l.readLock().lock(); @@ -189,10 +191,10 @@ public abstract class IntervalTreeImpl extends RedBla int height = 0; long path = 0; // path to this node from the root; 0 bit means we choose left subtree, 1 bit means we choose right subtree while (node != treeRoot) { - node.unpackCachedValuesTo(cached); - if (node.isValid() && cached.modCount == treeModCount) { - deltaUp = cached.deltaUpToRoot - node.delta; - allDeltasAreNull = cached.allDeltasUpAreNull; + long nodePackedOffsets = node.cachedDeltaUpToRoot; + if (node.isValid() && modCount(nodePackedOffsets) == treeModCount) { + deltaUp = deltaUpToRoot(nodePackedOffsets) - node.delta; + allDeltasAreNull = allDeltasUpAreNull(nodePackedOffsets); break; } IntervalNode parent = node.getParent(); @@ -305,11 +307,14 @@ public abstract class IntervalTreeImpl extends RedBla return cachedDeltaUpdater.compareAndSetLong(this, oldValue, newValue); } - public void unpackCachedValuesTo(NodeCachedOffsets t) { - long value = cachedDeltaUpToRoot; - t.deltaUpToRoot = (int)(value >> 33); - t.modCount = (int)value; - t.allDeltasUpAreNull = ((value >> 32) & 1) != 0; + private static boolean allDeltasUpAreNull(long packedOffsets) { + return ((packedOffsets >> 32) & 1) != 0; + } + private static int modCount(long packedOffsets) { + return (int)packedOffsets; + } + private static int deltaUpToRoot(long packedOffsets) { + return (int)(packedOffsets >> 33); } @NonNls @@ -319,12 +324,6 @@ public abstract class IntervalTreeImpl extends RedBla } } - static class NodeCachedOffsets { - private int modCount; // if it equals to the com.intellij.openapi.editor.impl.RedBlackTree.modCount then deltaUpToRoot can be used, otherwise it is expired - private int deltaUpToRoot; // sum of all deltas up to the root (including this node' delta). Has valid value only if modCount == IntervalTreeImpl.this.modCount - private boolean allDeltasUpAreNull; // true if all deltas up the tree (including this node) are 0. Has valid value only if modCount == IntervalTreeImpl.this.modCount - } - private void assertUnderWriteLock() { assert isAcquired(l.writeLock()) : l.writeLock(); } @@ -333,12 +332,12 @@ public abstract class IntervalTreeImpl extends RedBla return s.contains("Locked by thread"); } - private void pushDeltaFromRoot(IntervalNode node, NodeCachedOffsets cached) { + private void pushDeltaFromRoot(IntervalNode node) { if (node != null) { - node.unpackCachedValuesTo(cached); - if (cached.allDeltasUpAreNull && node.isValid() && cached.modCount == modCount) return; - pushDeltaFromRoot(node.getParent(), cached); - pushDelta(node, cached); + long packedOffsets = node.cachedDeltaUpToRoot; + if (IntervalNode.allDeltasUpAreNull(packedOffsets) && node.isValid() && IntervalNode.modCount(packedOffsets) == modCount) return; + pushDeltaFromRoot(node.getParent()); + pushDelta(node); } } @@ -672,14 +671,13 @@ public abstract class IntervalTreeImpl extends RedBla node.setRight(null); List> gced = new SmartList>(); - NodeCachedOffsets cached = new NodeCachedOffsets(); if (root == null) { root = node; } else { IntervalNode current = getRoot(); while (true) { - pushDelta(current, cached); + pushDelta(current); int compResult = compareNodes(node, 0, current, 0, gced); if (compResult == 0) { return current; @@ -702,7 +700,7 @@ public abstract class IntervalTreeImpl extends RedBla node.setParent(current); } node.setCachedValues(0, true, modCount); - correctMaxUp(node, cached); + correctMaxUp(node); onInsertNode(); keySize += node.intervals.size(); insertCase1(node); @@ -782,11 +780,10 @@ public abstract class IntervalTreeImpl extends RedBla int[] nodeCounter, TLongHashSet ids, boolean allDeltasUpAreNull) { if (root == null) return Trinity.create(Integer.MAX_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE); - NodeCachedOffsets cached = new NodeCachedOffsets(); - root.unpackCachedValuesTo(cached); - if (cached.modCount == modCount) { - assert cached.allDeltasUpAreNull == (root.delta == 0 && allDeltasUpAreNull); - assert cached.deltaUpToRoot == root.delta + deltaUpToRootExclusive; + long packedOffsets = root.cachedDeltaUpToRoot; + if (IntervalNode.modCount(packedOffsets) == modCount) { + assert IntervalNode.allDeltasUpAreNull(packedOffsets) == (root.delta == 0 && allDeltasUpAreNull); + assert IntervalNode.deltaUpToRoot(packedOffsets) == root.delta + deltaUpToRootExclusive; } T liveInterval = null; for (int i = root.intervals.size() - 1; i >= 0; i--) { @@ -839,12 +836,11 @@ public abstract class IntervalTreeImpl extends RedBla @Override protected Node maximumNode(Node n) { IntervalNode root = (IntervalNode)n; - NodeCachedOffsets cached = new NodeCachedOffsets(); - pushDelta(root.getParent(), cached); - pushDelta(root, cached); + pushDelta(root.getParent()); + pushDelta(root); while (root.getRight() != null) { root = root.getRight(); - pushDelta(root, cached); + pushDelta(root); } return root; } @@ -906,16 +902,15 @@ public abstract class IntervalTreeImpl extends RedBla void removeNode(@NotNull IntervalNode node) { deleteNode(node); IntervalNode parent = node.getParent(); - correctMaxUp(parent, new NodeCachedOffsets()); + correctMaxUp(parent); } @Override protected void deleteNode(@NotNull Node n) { assertUnderWriteLock(); IntervalNode node = (IntervalNode)n; - NodeCachedOffsets cached = new NodeCachedOffsets(); - pushDeltaFromRoot(node, cached); - assertAllDeltasAreNull(node, cached); + pushDeltaFromRoot(node); + assertAllDeltasAreNull(node); super.deleteNode(n); keySize -= node.intervals.size(); @@ -928,10 +923,10 @@ public abstract class IntervalTreeImpl extends RedBla } // returns true if all deltas involved are still 0 - protected boolean pushDelta(IntervalNode root, NodeCachedOffsets cached) { + protected boolean pushDelta(IntervalNode root) { if (root == null || !root.isValid()) return true; IntervalNode parent = root.getParent(); - assertAllDeltasAreNull(parent, cached); + assertAllDeltasAreNull(parent); int delta = root.delta; root.setCachedValues(0, true, 0); if (delta != 0) { @@ -984,7 +979,7 @@ public abstract class IntervalTreeImpl extends RedBla //correctMaxUp(a); a.color = dcolor; d.color = acolor; - correctMaxUp(a, new NodeCachedOffsets()); + correctMaxUp(a); checkMax(false); assert a.delta == 0 : a.delta; @@ -1044,8 +1039,8 @@ public abstract class IntervalTreeImpl extends RedBla node.maxEnd = realMax - deltaUpToRoot; } - private void correctMaxUp(IntervalNode node, NodeCachedOffsets cached) { - int delta = node == null ? 0 : node.computeDeltaUpToRoot(cached); + private void correctMaxUp(IntervalNode node) { + int delta = node == null ? 0 : node.computeDeltaUpToRoot(); assert delta == 0 : delta; while (node != null) { if (node.isValid()) { @@ -1065,12 +1060,11 @@ public abstract class IntervalTreeImpl extends RedBla IntervalNode node2 = node1.getLeft(); IntervalNode node3 = node1.getRight(); - NodeCachedOffsets cached = new NodeCachedOffsets(); IntervalNode parent = node1.getParent(); - int deltaUp = parent == null ? 0 : parent.computeDeltaUpToRoot(cached); - pushDelta(node1, cached); - pushDelta(node2, cached); - pushDelta(node3, cached); + int deltaUp = parent == null ? 0 : parent.computeDeltaUpToRoot(); + pushDelta(node1); + pushDelta(node2); + pushDelta(node3); super.rotateRight(node1); @@ -1079,9 +1073,9 @@ public abstract class IntervalTreeImpl extends RedBla } correctMax(node1, deltaUp); correctMax(node2, deltaUp); - assertAllDeltasAreNull(node1, cached); - assertAllDeltasAreNull(node2, cached); - assertAllDeltasAreNull(node3, cached); + assertAllDeltasAreNull(node1); + assertAllDeltasAreNull(node2); + assertAllDeltasAreNull(node3); checkMax(false); } @@ -1092,12 +1086,11 @@ public abstract class IntervalTreeImpl extends RedBla IntervalNode node2 = node1.getLeft(); IntervalNode node3 = node1.getRight(); - NodeCachedOffsets cached = new NodeCachedOffsets(); IntervalNode parent = node1.getParent(); - int deltaUp = parent == null ? 0 : parent.computeDeltaUpToRoot(cached); - pushDelta(node1, cached); - pushDelta(node2, cached); - pushDelta(node3, cached); + int deltaUp = parent == null ? 0 : parent.computeDeltaUpToRoot(); + pushDelta(node1); + pushDelta(node2); + pushDelta(node3); checkMax(false); super.rotateLeft(node1); @@ -1106,9 +1099,9 @@ public abstract class IntervalTreeImpl extends RedBla } correctMax(node1, deltaUp); correctMax(node3, deltaUp); - assertAllDeltasAreNull(node1, cached); - assertAllDeltasAreNull(node2, cached); - assertAllDeltasAreNull(node3, cached); + assertAllDeltasAreNull(node1); + assertAllDeltasAreNull(node2); + assertAllDeltasAreNull(node3); checkMax(false); } @@ -1116,9 +1109,8 @@ public abstract class IntervalTreeImpl extends RedBla @Override protected void replaceNode(@NotNull Node node, Node child) { IntervalNode myNode = (IntervalNode)node; - NodeCachedOffsets cached = new NodeCachedOffsets(); - pushDelta(myNode, cached); - pushDelta((IntervalNode)child, cached); + pushDelta(myNode); + pushDelta((IntervalNode)child); super.replaceNode(node, child); if (child != null && myNode.isValid()) { @@ -1127,12 +1119,12 @@ public abstract class IntervalTreeImpl extends RedBla } } - private void assertAllDeltasAreNull(IntervalNode node, NodeCachedOffsets cached) { + private void assertAllDeltasAreNull(IntervalNode node) { if (node == null) return; if (!node.isValid()) return; assert node.delta == 0; - node.unpackCachedValuesTo(cached); - assert cached.modCount != modCount || cached.allDeltasUpAreNull; + long packedOffsets = node.cachedDeltaUpToRoot; + assert IntervalNode.modCount(packedOffsets) != modCount || IntervalNode.allDeltasUpAreNull(packedOffsets); } private IntervalNode findMinOverlappingWith(IntervalNode root, Interval interval, int modCountBefore, int deltaUpToRootExclusive) { diff --git a/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java b/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java index c82d44e5a1bf..bd320dfc7462 100644 --- a/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java +++ b/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java @@ -187,7 +187,7 @@ public class RangeMarkerTree extends IntervalTreeImpl> affected = new SmartList>(); - collectAffectedMarkersAndShiftSubtrees(getRoot(), e, affected, new NodeCachedOffsets()); + collectAffectedMarkersAndShiftSubtrees(getRoot(), e, affected); checkMax(false); if (!affected.isEmpty()) { @@ -257,9 +257,9 @@ public class RangeMarkerTree extends IntervalTreeImpl root, @NotNull DocumentEvent e, - @NotNull List> affected, NodeCachedOffsets cached) { + @NotNull List> affected) { if (root == null) return true; - boolean norm = pushDelta(root, cached); + boolean norm = pushDelta(root); int maxEnd = root.maxEnd; assert root.isValid(); @@ -284,8 +284,8 @@ public class RangeMarkerTree extends IntervalTreeImpl extends IntervalTreeImpl= 0 && selEnd >= 0) { myEditor.getSelectionModel().setSelection(mySegments.getSegmentStart(selStart), mySegments.getSegmentStart(selEnd)); } - fireBeforeTemplateFinished(); final Editor editor = myEditor; + fireBeforeTemplateFinished(); int oldVar = myCurrentVariableNumber; setCurrentVariableNumber(-1); currentVariableChanged(oldVar); diff --git a/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesManager.java b/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesManager.java index 1682455dfe00..e6bba8de2ff4 100644 --- a/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesManager.java +++ b/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesManager.java @@ -403,7 +403,7 @@ public class FindUsagesManager implements JDOMExternalizable { .processRequests(options.fastTrack, new ReadActionProcessor() { @Override public boolean processInReadAction(final PsiReference ref) { - return usageInfoProcessor.process(new UsageInfo(ref)); + return !ref.getElement().isValid() || usageInfoProcessor.process(new UsageInfo(ref)); } }); } diff --git a/platform/lang-impl/src/com/intellij/ide/actions/GotoRelatedFileAction.java b/platform/lang-impl/src/com/intellij/ide/actions/GotoRelatedFileAction.java index c6bb21885a87..79c9b76eb08e 100644 --- a/platform/lang-impl/src/com/intellij/ide/actions/GotoRelatedFileAction.java +++ b/platform/lang-impl/src/com/intellij/ide/actions/GotoRelatedFileAction.java @@ -174,6 +174,16 @@ public class GotoRelatedFileAction extends AnAction { return true; } + @Override + public String getIndexedString(Object value) { + if (value instanceof GotoRelatedItem) { + //noinspection ConstantConditions + return ((GotoRelatedItem)value).getCustomName(); + } + final PsiElement element = (PsiElement)value; + return renderer.getElementText(element) + " " + renderer.getContainerText(element, null); + } + @Override public PopupStep onChosen(Object selectedValue, boolean finalChoice) { processor.process(selectedValue); diff --git a/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java b/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java index a59da7d7910a..d5e7b3be28d6 100644 --- a/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java +++ b/platform/lang-impl/src/com/intellij/ide/bookmarks/actions/BookmarksAction.java @@ -195,7 +195,7 @@ public class BookmarksAction extends AnAction implements DumbAware { ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar("", actions, true); actionToolbar.setReservePlaceAutoPopupIcon(false); - actionToolbar.setMinimumButtonSize(new Dimension(16, 16)); + actionToolbar.setMinimumButtonSize(new Dimension(20, 20)); final JComponent toolBar = actionToolbar.getComponent(); toolBar.setOpaque(false); diff --git a/platform/lang-impl/src/com/intellij/ide/commander/ProjectListBuilder.java b/platform/lang-impl/src/com/intellij/ide/commander/ProjectListBuilder.java index cc59262ca1ad..49b70699a087 100644 --- a/platform/lang-impl/src/com/intellij/ide/commander/ProjectListBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/commander/ProjectListBuilder.java @@ -31,6 +31,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.Alarm; +import org.jetbrains.annotations.NotNull; import java.awt.datatransfer.Transferable; import java.util.ArrayList; @@ -146,30 +147,30 @@ public class ProjectListBuilder extends AbstractListBuilder { myOutOfCodeBlockModificationCount = myModificationTracker.getOutOfCodeBlockModificationCount(); } - public void childRemoved(final PsiTreeChangeEvent event) { + public void childRemoved(@NotNull final PsiTreeChangeEvent event) { final PsiElement child = event.getOldChild(); if (child instanceof PsiWhiteSpace) return; //optimization childrenChanged(); } - public void childAdded(final PsiTreeChangeEvent event) { + public void childAdded(@NotNull final PsiTreeChangeEvent event) { final PsiElement child = event.getNewChild(); if (child instanceof PsiWhiteSpace) return; //optimization childrenChanged(); } - public void childReplaced(final PsiTreeChangeEvent event) { + public void childReplaced(@NotNull final PsiTreeChangeEvent event) { final PsiElement oldChild = event.getOldChild(); final PsiElement newChild = event.getNewChild(); if (oldChild instanceof PsiWhiteSpace && newChild instanceof PsiWhiteSpace) return; //optimization childrenChanged(); } - public void childMoved(final PsiTreeChangeEvent event) { + public void childMoved(@NotNull final PsiTreeChangeEvent event) { childrenChanged(); } - public void childrenChanged(final PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull final PsiTreeChangeEvent event) { childrenChanged(); } @@ -180,7 +181,7 @@ public class ProjectListBuilder extends AbstractListBuilder { addUpdateRequest(); } - public void propertyChanged(final PsiTreeChangeEvent event) { + public void propertyChanged(@NotNull final PsiTreeChangeEvent event) { final String propertyName = event.getPropertyName(); if (propertyName.equals(PsiTreeChangeEvent.PROP_ROOTS)) { addUpdateRequest(); diff --git a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesManager.java b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesManager.java index b7bd1e902fec..44744c76c999 100644 --- a/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesManager.java +++ b/platform/lang-impl/src/com/intellij/ide/favoritesTreeView/FavoritesManager.java @@ -378,7 +378,7 @@ public class FavoritesManager implements ProjectComponent, JDOMExternalizable { } private class MyRootsChangeAdapter extends PsiTreeChangeAdapter { - public void beforeChildMovement(final PsiTreeChangeEvent event) { + public void beforeChildMovement(@NotNull final PsiTreeChangeEvent event) { final PsiElement oldParent = event.getOldParent(); final PsiElement newParent = event.getNewParent(); final PsiElement child = event.getChild(); @@ -417,7 +417,7 @@ public class FavoritesManager implements ProjectComponent, JDOMExternalizable { } } - public void beforePropertyChange(final PsiTreeChangeEvent event) { + public void beforePropertyChange(@NotNull final PsiTreeChangeEvent event) { if (event.getPropertyName().equals(PsiTreeChangeEvent.PROP_FILE_NAME) || event.getPropertyName().equals(PsiTreeChangeEvent.PROP_DIRECTORY_NAME)) { final PsiElement psiElement = event.getChild(); if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) { diff --git a/platform/lang-impl/src/com/intellij/ide/hierarchy/HierarchyTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/hierarchy/HierarchyTreeBuilder.java index f54e41dbae83..5c1aac4bf57b 100644 --- a/platform/lang-impl/src/com/intellij/ide/hierarchy/HierarchyTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/hierarchy/HierarchyTreeBuilder.java @@ -110,27 +110,27 @@ public class HierarchyTreeBuilder extends AbstractTreeBuilder { } private final class MyPsiTreeChangeListener extends PsiTreeChangeAdapter { - public final void childAdded(final PsiTreeChangeEvent event) { + public final void childAdded(@NotNull final PsiTreeChangeEvent event) { getUpdater().addSubtreeToUpdate(getRootNode()); } - public final void childRemoved(final PsiTreeChangeEvent event) { + public final void childRemoved(@NotNull final PsiTreeChangeEvent event) { getUpdater().addSubtreeToUpdate(getRootNode()); } - public final void childReplaced(final PsiTreeChangeEvent event) { + public final void childReplaced(@NotNull final PsiTreeChangeEvent event) { getUpdater().addSubtreeToUpdate(getRootNode()); } - public final void childMoved(final PsiTreeChangeEvent event) { + public final void childMoved(@NotNull final PsiTreeChangeEvent event) { getUpdater().addSubtreeToUpdate(getRootNode()); } - public final void childrenChanged(final PsiTreeChangeEvent event) { + public final void childrenChanged(@NotNull final PsiTreeChangeEvent event) { getUpdater().addSubtreeToUpdate(getRootNode()); } - public final void propertyChanged(final PsiTreeChangeEvent event) { + public final void propertyChanged(@NotNull final PsiTreeChangeEvent event) { getUpdater().addSubtreeToUpdate(getRootNode()); } } diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarListener.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarListener.java index fa7513d1c44d..634501e5e74b 100644 --- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarListener.java +++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarListener.java @@ -184,23 +184,23 @@ public class NavBarListener extends WolfTheProblemSolver.ProblemListener rebuildUI(); } - public void childAdded(PsiTreeChangeEvent event) { + public void childAdded(@NotNull PsiTreeChangeEvent event) { updateModel(); } - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { updateModel(); } - public void childMoved(PsiTreeChangeEvent event) { + public void childMoved(@NotNull PsiTreeChangeEvent event) { updateModel(); } - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { updateModel(); } - public void propertyChanged(final PsiTreeChangeEvent event) { + public void propertyChanged(@NotNull final PsiTreeChangeEvent event) { updateModel(); } @@ -267,23 +267,23 @@ public class NavBarListener extends WolfTheProblemSolver.ProblemListener public void beforeRootsChange(ModuleRootEvent event) {} @Override - public void beforeChildAddition(PsiTreeChangeEvent event) {} + public void beforeChildAddition(@NotNull PsiTreeChangeEvent event) {} @Override - public void beforeChildRemoval(PsiTreeChangeEvent event) {} + public void beforeChildRemoval(@NotNull PsiTreeChangeEvent event) {} @Override - public void beforeChildReplacement(PsiTreeChangeEvent event) {} + public void beforeChildReplacement(@NotNull PsiTreeChangeEvent event) {} @Override - public void beforeChildMovement(PsiTreeChangeEvent event) {} + public void beforeChildMovement(@NotNull PsiTreeChangeEvent event) {} @Override - public void beforeChildrenChange(PsiTreeChangeEvent event) {} + public void beforeChildrenChange(@NotNull PsiTreeChangeEvent event) {} @Override - public void beforePropertyChange(PsiTreeChangeEvent event) {} + public void beforePropertyChange(@NotNull PsiTreeChangeEvent event) {} @Override - public void childRemoved(PsiTreeChangeEvent event) {} + public void childRemoved(@NotNull PsiTreeChangeEvent event) {} } diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/ProjectViewPsiTreeChangeListener.java b/platform/lang-impl/src/com/intellij/ide/projectView/ProjectViewPsiTreeChangeListener.java index 7ef50c1d79ca..dec90ca3c785 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/ProjectViewPsiTreeChangeListener.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/ProjectViewPsiTreeChangeListener.java @@ -23,6 +23,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.util.PsiModificationTracker; +import org.jetbrains.annotations.NotNull; import javax.swing.tree.DefaultMutableTreeNode; @@ -43,31 +44,31 @@ public abstract class ProjectViewPsiTreeChangeListener extends PsiTreeChangeAdap protected abstract DefaultMutableTreeNode getRootNode(); - public final void childRemoved(PsiTreeChangeEvent event) { + public final void childRemoved(@NotNull PsiTreeChangeEvent event) { PsiElement child = event.getOldChild(); if (child instanceof PsiWhiteSpace) return; //optimization childrenChanged(event.getParent(), true); } - public final void childAdded(PsiTreeChangeEvent event) { + public final void childAdded(@NotNull PsiTreeChangeEvent event) { PsiElement child = event.getNewChild(); if (child instanceof PsiWhiteSpace) return; //optimization childrenChanged(event.getParent(), true); } - public final void childReplaced(PsiTreeChangeEvent event) { + public final void childReplaced(@NotNull PsiTreeChangeEvent event) { PsiElement oldChild = event.getOldChild(); PsiElement newChild = event.getNewChild(); if (oldChild instanceof PsiWhiteSpace && newChild instanceof PsiWhiteSpace) return; //optimization childrenChanged(event.getParent(), true); } - public final void childMoved(PsiTreeChangeEvent event) { + public final void childMoved(@NotNull PsiTreeChangeEvent event) { childrenChanged(event.getOldParent(), false); childrenChanged(event.getNewParent(), true); } - public final void childrenChanged(PsiTreeChangeEvent event) { + public final void childrenChanged(@NotNull PsiTreeChangeEvent event) { childrenChanged(event.getParent(), true); } @@ -104,7 +105,7 @@ public abstract class ProjectViewPsiTreeChangeListener extends PsiTreeChangeAdap } } - public void propertyChanged(PsiTreeChangeEvent event) { + public void propertyChanged(@NotNull PsiTreeChangeEvent event) { String propertyName = event.getPropertyName(); PsiElement element = event.getElement(); DefaultMutableTreeNode rootNode = getRootNode(); diff --git a/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java b/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java index 03f1c39ea5e6..3abc03715a52 100644 --- a/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/scopeView/ScopeTreeViewPanel.java @@ -513,7 +513,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { } private class MyPsiTreeChangeAdapter extends PsiTreeChangeAdapter { - public void childAdded(final PsiTreeChangeEvent event) { + public void childAdded(@NotNull final PsiTreeChangeEvent event) { final PsiElement element = event.getParent(); final PsiElement child = event.getChild(); if (child == null) return; @@ -549,7 +549,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { } } - public void beforeChildRemoval(final PsiTreeChangeEvent event) { + public void beforeChildRemoval(@NotNull final PsiTreeChangeEvent event) { final PsiElement child = event.getChild(); final PsiElement parent = event.getParent(); if (parent instanceof PsiDirectory && (child instanceof PsiFile && !isInjected((PsiFile)child) || child instanceof PsiDirectory)) { @@ -565,7 +565,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { } @Override - public void beforeChildMovement(PsiTreeChangeEvent event) { + public void beforeChildMovement(@NotNull PsiTreeChangeEvent event) { final PsiElement oldParent = event.getOldParent(); final PsiElement child = event.getChild(); if (oldParent instanceof PsiDirectory) { @@ -583,7 +583,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { } } - public void childMoved(PsiTreeChangeEvent event) { + public void childMoved(@NotNull PsiTreeChangeEvent event) { final PsiElement newParent = event.getNewParent(); final PsiElement child = event.getChild(); if (newParent instanceof PsiDirectory) { @@ -611,7 +611,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { } - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { final PsiElement parent = event.getParent(); final PsiFile file = parent.getContainingFile(); if (file != null && file.getFileType() == StdFileTypes.JAVA) { @@ -631,7 +631,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { } } - public final void propertyChanged(PsiTreeChangeEvent event) { + public final void propertyChanged(@NotNull PsiTreeChangeEvent event) { String propertyName = event.getPropertyName(); final PsiElement element = event.getElement(); if (element != null) { @@ -651,7 +651,7 @@ public class ScopeTreeViewPanel extends JPanel implements Disposable { } } - public void childReplaced(final PsiTreeChangeEvent event) { + public void childReplaced(@NotNull final PsiTreeChangeEvent event) { final NamedScope scope = getCurrentScope(); final PsiElement element = event.getNewChild(); final PsiFile psiFile = event.getFile(); diff --git a/platform/lang-impl/src/com/intellij/ide/structureView/impl/TemplateLanguageStructureViewBuilder.java b/platform/lang-impl/src/com/intellij/ide/structureView/impl/TemplateLanguageStructureViewBuilder.java index 896321962e12..2b67e2216d2a 100644 --- a/platform/lang-impl/src/com/intellij/ide/structureView/impl/TemplateLanguageStructureViewBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/structureView/impl/TemplateLanguageStructureViewBuilder.java @@ -62,24 +62,24 @@ public abstract class TemplateLanguageStructureViewBuilder implements StructureV myProject = psiElement.getProject(); myPsiTreeChangeAdapter = new PsiTreeChangeAdapter() { - public void childAdded(PsiTreeChangeEvent event) { + public void childAdded(@NotNull PsiTreeChangeEvent event) { childrenChanged(event); } - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { childrenChanged(event); } - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { childrenChanged(event); } - public void childMoved(PsiTreeChangeEvent event) { + public void childMoved(@NotNull PsiTreeChangeEvent event) { childrenChanged(event); } final Alarm myAlarm = new Alarm(); - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { myAlarm.cancelAllRequests(); myAlarm.addRequest(new Runnable(){ public void run() { diff --git a/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java index 1e0f4a6c369d..072037cd97d2 100644 --- a/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/structureView/newStructureView/StructureTreeBuilder.java @@ -136,20 +136,20 @@ public class StructureTreeBuilder extends AbstractTreeBuilder { myOutOfCodeBlockModificationCount = myModificationTracker.getOutOfCodeBlockModificationCount(); } - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { PsiElement child = event.getOldChild(); if (child instanceof PsiWhiteSpace) return; //optimization childrenChanged(); } - public void childAdded(PsiTreeChangeEvent event) { + public void childAdded(@NotNull PsiTreeChangeEvent event) { PsiElement child = event.getNewChild(); if (child instanceof PsiWhiteSpace) return; //optimization childrenChanged(); } - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { /** Test comment */ PsiElement oldChild = event.getOldChild(); PsiElement newChild = event.getNewChild(); @@ -157,11 +157,11 @@ public class StructureTreeBuilder extends AbstractTreeBuilder { childrenChanged(); } - public void childMoved(PsiTreeChangeEvent event) { + public void childMoved(@NotNull PsiTreeChangeEvent event) { childrenChanged(); } - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { childrenChanged(); } @@ -172,7 +172,7 @@ public class StructureTreeBuilder extends AbstractTreeBuilder { setupUpdateAlarm(); } - public void propertyChanged(PsiTreeChangeEvent event) { + public void propertyChanged(@NotNull PsiTreeChangeEvent event) { childrenChanged(); } } diff --git a/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java b/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java index 156ee77bd161..fa524d04a5bc 100644 --- a/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java +++ b/platform/lang-impl/src/com/intellij/ide/todo/TodoTreeBuilder.java @@ -658,7 +658,7 @@ public abstract class TodoTreeBuilder extends AbstractTreeBuilder { } private final class MyPsiTreeChangeListener extends PsiTreeChangeAdapter { - public void childAdded(PsiTreeChangeEvent e) { + public void childAdded(@NotNull PsiTreeChangeEvent e) { // If local modification if (e.getFile() != null) { markFileAsDirty(e.getFile()); @@ -675,7 +675,7 @@ public abstract class TodoTreeBuilder extends AbstractTreeBuilder { updateTree(true); } - public void beforeChildRemoval(PsiTreeChangeEvent e) { + public void beforeChildRemoval(@NotNull PsiTreeChangeEvent e) { // If local midification final PsiFile file = e.getFile(); if (file != null) { @@ -711,7 +711,7 @@ public abstract class TodoTreeBuilder extends AbstractTreeBuilder { } } - public void childMoved(PsiTreeChangeEvent e) { + public void childMoved(@NotNull PsiTreeChangeEvent e) { if (e.getFile() != null) { // local change markFileAsDirty(e.getFile()); updateTree(true); @@ -744,21 +744,21 @@ public abstract class TodoTreeBuilder extends AbstractTreeBuilder { } } - public void childReplaced(PsiTreeChangeEvent e) { + public void childReplaced(@NotNull PsiTreeChangeEvent e) { if (e.getFile() != null) { markFileAsDirty(e.getFile()); updateTree(true); } } - public void childrenChanged(PsiTreeChangeEvent e) { + public void childrenChanged(@NotNull PsiTreeChangeEvent e) { if (e.getFile() != null) { markFileAsDirty(e.getFile()); updateTree(true); } } - public void propertyChanged(PsiTreeChangeEvent e) { + public void propertyChanged(@NotNull PsiTreeChangeEvent e) { String propertyName = e.getPropertyName(); if (propertyName.equals(PsiTreeChangeEvent.PROP_ROOTS)) { // rebuild all tree when source roots were changed getUpdater().runBeforeUpdate( diff --git a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/PsiAwareFileEditorManagerImpl.java b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/PsiAwareFileEditorManagerImpl.java index 6d107ca159dd..d5761461754b 100644 --- a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/PsiAwareFileEditorManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/PsiAwareFileEditorManagerImpl.java @@ -106,7 +106,7 @@ public class PsiAwareFileEditorManagerImpl extends FileEditorManagerImpl { * Updates attribute of open files when roots change */ private final class MyPsiTreeChangeListener extends PsiTreeChangeAdapter { - public void propertyChanged(final PsiTreeChangeEvent e) { + public void propertyChanged(@NotNull final PsiTreeChangeEvent e) { if (PsiTreeChangeEvent.PROP_ROOTS.equals(e.getPropertyName())) { ApplicationManager.getApplication().assertIsDispatchThread(); final VirtualFile[] openFiles = getOpenFiles(); @@ -118,23 +118,23 @@ public class PsiAwareFileEditorManagerImpl extends FileEditorManagerImpl { } } - public void childAdded(PsiTreeChangeEvent event) { + public void childAdded(@NotNull PsiTreeChangeEvent event) { doChange(event); } - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { doChange(event); } - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { doChange(event); } - public void childMoved(PsiTreeChangeEvent event) { + public void childMoved(@NotNull PsiTreeChangeEvent event) { doChange(event); } - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { doChange(event); } diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerImpl.java b/platform/lang-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerImpl.java index a5ddbb3c7a6a..811aa5dce501 100644 --- a/platform/lang-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/openapi/roots/impl/ProjectRootManagerImpl.java @@ -730,7 +730,7 @@ public class ProjectRootManagerImpl extends ProjectRootManagerEx implements Proj } private class MyVirtualFilePointerListener implements VirtualFilePointerListener { - public void beforeValidityChanged(VirtualFilePointer[] pointers) { + public void beforeValidityChanged(@NotNull VirtualFilePointer[] pointers) { if (!myProject.isDisposed()) { if (myInsideRefresh == 0) { if (affectsRoots(pointers)) { @@ -747,7 +747,7 @@ public class ProjectRootManagerImpl extends ProjectRootManagerEx implements Proj } } - public void validityChanged(VirtualFilePointer[] pointers) { + public void validityChanged(@NotNull VirtualFilePointer[] pointers) { if (!myProject.isDisposed()) { if (myInsideRefresh > 0) { clearScopesCaches(); diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionToolsConfigurable.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionToolsConfigurable.java index 4f336fc92a80..f97a5e122cb1 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionToolsConfigurable.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/InspectionToolsConfigurable.java @@ -49,6 +49,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.profile.Profile; +import com.intellij.profile.ProfileManager; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.ui.components.JBScrollPane; @@ -99,7 +100,8 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable imple InspectionToolRegistrar.getInstance().buildInspectionSearchIndexIfNecessary(); myAddButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - final ModifiableModel model = SingleInspectionProfilePanel.createNewProfile(-1, getSelectedObject(), myWholePanel, ""); + final Set existingProfileNames = myPanels.keySet(); + final ModifiableModel model = SingleInspectionProfilePanel.createNewProfile(-1, getSelectedObject(), myWholePanel, "", existingProfileNames); if (model != null) { addProfile((InspectionProfileImpl)model); myDeletedProfiles.remove(model.getName()); @@ -113,7 +115,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable imple final InspectionProfileImpl selectedProfile = (InspectionProfileImpl)myProfiles.getSelectedItem(); ((DefaultComboBoxModel)myProfiles.getModel()).removeElement(selectedProfile); myDeletedProfiles.add(selectedProfile.getName()); - myDeleteButton.setEnabled(myProfiles.getModel().getSize() > 1); + myDeleteButton.setEnabled(isDeleteEnabled(selectedProfile)); } }); @@ -216,7 +218,9 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable imple myCopyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - final InspectionProfileImpl model = (InspectionProfileImpl)SingleInspectionProfilePanel.createNewProfile(0, getSelectedObject(), myWholePanel, ""); + final Set existingProfileNames = myPanels.keySet(); + final InspectionProfileImpl model = (InspectionProfileImpl) + SingleInspectionProfilePanel.createNewProfile(0, getSelectedObject(), myWholePanel, "", existingProfileNames); if (model != null) { final InspectionProfileImpl modifiableModel = (InspectionProfileImpl)model.getModifiableModel(); modifiableModel.setModified(true); @@ -285,7 +289,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable imple myProfiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final InspectionProfileImpl profile = (InspectionProfileImpl)myProfiles.getSelectedItem(); - myDeleteButton.setEnabled(myProfiles.getModel().getSize() > 1); + myDeleteButton.setEnabled(isDeleteEnabled(profile)); myLayout.show(myPanel, profile.getName()); SingleInspectionProfilePanel panel = getSelectedPanel(); if (panel != null) { @@ -352,7 +356,7 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable imple final InspectionProfileImpl inspectionProfile = getCurrentProfile(); myProfiles.setSelectedItem(inspectionProfile); myLayout.show(myPanel, inspectionProfile.getName()); - myDeleteButton.setEnabled(getProfiles().size() > 1 && inspectionProfile.getProfileManager() == myProfileManager); + myDeleteButton.setEnabled(isDeleteEnabled(inspectionProfile)); final SingleInspectionProfilePanel panel = getSelectedPanel(); if (panel != null) { panel.setVisible(true);//make sure that UI was initialized @@ -373,6 +377,26 @@ public abstract class InspectionToolsConfigurable extends BaseConfigurable imple } } + private boolean isDeleteEnabled(InspectionProfileImpl inspectionProfile) { + final ProfileManager profileManager = inspectionProfile.getProfileManager(); + + boolean projectProfileFound = false; + boolean ideProfileFound = false; + + final ComboBoxModel model = myProfiles.getModel(); + for (int i = 0; i < model.getSize(); i++) { + Profile profile = (Profile)model.getElementAt(i); + if (inspectionProfile == profile) continue; + final boolean isProjectProfile = profile.getProfileManager() == myProjectProfileManager; + projectProfileFound |= isProjectProfile; + ideProfileFound |= !isProjectProfile; + + if (ideProfileFound && projectProfileFound) break; + } + + return profileManager == myProjectProfileManager ? projectProfileFound : ideProfileFound; + } + protected Collection getProfiles() { final Collection result = new ArrayList(); result.addAll(myProfileManager.getProfiles()); diff --git a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java index dd3ebd75c5a5..ba2c682d3ecf 100644 --- a/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java +++ b/platform/lang-impl/src/com/intellij/profile/codeInspection/ui/SingleInspectionProfilePanel.java @@ -59,7 +59,6 @@ import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.ui.*; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.Alarm; -import com.intellij.util.ArrayUtil; import com.intellij.util.config.StorageAccessors; import com.intellij.util.containers.Convertor; import com.intellij.util.ui.UIUtil; @@ -262,12 +261,12 @@ public class SingleInspectionProfilePanel extends JPanel { public static ModifiableModel createNewProfile(final int initValue, ModifiableModel selectedProfile, JPanel parent, - String profileName) { - + String profileName, + Set existingProfileNames) { profileName = Messages.showInputDialog(parent, profileName, "Create New Inspection Profile", Messages.getQuestionIcon()); if (profileName == null) return null; final ProfileManager profileManager = selectedProfile.getProfileManager(); - if (ArrayUtil.find(profileManager.getAvailableProfileNames(), profileName) != -1) { + if (existingProfileNames.contains(profileName)) { Messages.showErrorDialog(InspectionsBundle.message("inspection.unable.to.create.profile.message", profileName), InspectionsBundle.message("inspection.unable.to.create.profile.dialog.title")); return null; diff --git a/platform/lang-impl/src/com/intellij/psi/impl/PsiToDocumentSynchronizer.java b/platform/lang-impl/src/com/intellij/psi/impl/PsiToDocumentSynchronizer.java index a7178d262a44..89b421d2249c 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/PsiToDocumentSynchronizer.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/PsiToDocumentSynchronizer.java @@ -104,7 +104,7 @@ public class PsiToDocumentSynchronizer extends PsiTreeChangeAdapter { } @Override - public void childAdded(final PsiTreeChangeEvent event) { + public void childAdded(@NotNull final PsiTreeChangeEvent event) { doSync(event, false, new DocSyncAction() { @Override public void syncDocument(Document document, PsiTreeChangeEventImpl event) { @@ -114,7 +114,7 @@ public class PsiToDocumentSynchronizer extends PsiTreeChangeAdapter { } @Override - public void childRemoved(final PsiTreeChangeEvent event) { + public void childRemoved(@NotNull final PsiTreeChangeEvent event) { doSync(event, false, new DocSyncAction() { @Override public void syncDocument(Document document, PsiTreeChangeEventImpl event) { @@ -124,7 +124,7 @@ public class PsiToDocumentSynchronizer extends PsiTreeChangeAdapter { } @Override - public void childReplaced(final PsiTreeChangeEvent event) { + public void childReplaced(@NotNull final PsiTreeChangeEvent event) { doSync(event, false, new DocSyncAction() { @Override public void syncDocument(Document document, PsiTreeChangeEventImpl event) { @@ -134,7 +134,7 @@ public class PsiToDocumentSynchronizer extends PsiTreeChangeAdapter { } @Override - public void childrenChanged(final PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull final PsiTreeChangeEvent event) { doSync(event, false, new DocSyncAction() { @Override public void syncDocument(Document document, PsiTreeChangeEventImpl event) { diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java index 786c04e29069..3edcb908e65f 100644 --- a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java @@ -25,7 +25,6 @@ import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.components.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; @@ -218,7 +217,6 @@ public class StubIndexImpl extends StubIndex implements ApplicationComponent, Pe return container.forEach(new ValueContainer.ContainerAction() { @Override public boolean perform(final int id, @NotNull final TIntArrayList value) { - ProgressManager.checkCanceled(); if (projectFilesFilter != null && !projectFilesFilter.contains(id)) return true; final VirtualFile file = IndexInfrastructure.findFileByIdIfCached(fs, id); if (file == null || scope != null && !scope.contains(file)) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureGestureDetector.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureGestureDetector.java index 681884ea408a..7bf96c500769 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureGestureDetector.java +++ b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureGestureDetector.java @@ -160,7 +160,7 @@ public class ChangeSignatureGestureDetector extends PsiTreeChangeAdapter impleme } @Override - public void beforeChildRemoval(PsiTreeChangeEvent event) { + public void beforeChildRemoval(@NotNull PsiTreeChangeEvent event) { final PsiElement child = event.getChild(); if (child instanceof PsiFile) { final PsiFile psiFile = (PsiFile)child; @@ -177,17 +177,17 @@ public class ChangeSignatureGestureDetector extends PsiTreeChangeAdapter impleme } @Override - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { change(event.getParent()); } @Override - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { change(event.getChild()); } @Override - public void childAdded(PsiTreeChangeEvent event) { + public void childAdded(@NotNull PsiTreeChangeEvent event) { change(event.getChild()); } diff --git a/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/InplaceVariableIntroducer.java b/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/InplaceVariableIntroducer.java index 1a0027304954..5bf749e445e2 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/InplaceVariableIntroducer.java +++ b/platform/lang-impl/src/com/intellij/refactoring/introduce/inplace/InplaceVariableIntroducer.java @@ -17,6 +17,7 @@ package com.intellij.refactoring.introduce.inplace; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; +import com.intellij.codeInsight.template.ExpressionContext; import com.intellij.codeInsight.template.TextResult; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; @@ -33,10 +34,13 @@ import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.*; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNamedElement; +import com.intellij.psi.SmartPointerManager; +import com.intellij.psi.SmartPsiElementPointer; import com.intellij.psi.codeStyle.SuggestedNameInfo; import com.intellij.refactoring.rename.NameSuggestionProvider; import com.intellij.refactoring.rename.PreferrableNameSuggestionProvider; import com.intellij.refactoring.rename.inplace.InplaceRefactoring; +import com.intellij.refactoring.rename.inplace.MyLookupExpression; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.ui.PositionTracker; import org.jetbrains.annotations.Nullable; @@ -79,11 +83,6 @@ public abstract class InplaceVariableIntroducer extends In initOccurrencesMarkers(); } - @Deprecated - public boolean performInplaceRename() { - return performInplaceRefactoring(null); - } - @Override protected boolean shouldSelectAll() { return true; @@ -235,31 +234,61 @@ public abstract class InplaceVariableIntroducer extends In } @Override - protected LookupElement[] createLookupItems(LookupElement[] lookupItems, String name) { - TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); - final PsiNamedElement psiVariable = getVariable(); - if (psiVariable != null) { - final TextResult insertedValue = - templateState != null ? templateState.getVariableValue(PRIMARY_VARIABLE_NAME) : null; - if (insertedValue != null) { - final String text = insertedValue.getText(); - if (!text.isEmpty() && !Comparing.strEqual(text, name)) { - final LinkedHashSet names = new LinkedHashSet(); - names.add(text); - for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) { - final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(psiVariable, psiVariable, names); - if (suggestedNameInfo != null && provider instanceof PreferrableNameSuggestionProvider && !((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) break; - } - final LookupElement[] items = new LookupElement[names.size()]; - final Iterator iterator = names.iterator(); - for (int i = 0; i < items.length; i++) { - items[i] = LookupElementBuilder.create(iterator.next()); - } - return items; - } - } - } - return lookupItems; + protected MyLookupExpression createLookupExpression() { + return new MyIntroduceLookupExpression(getInitialName(), myNameSuggestions, myElementToRename, shouldSelectAll(), myAdvertisementText); } + private static class MyIntroduceLookupExpression extends MyLookupExpression { + private final SmartPsiElementPointer myPointer; + + public MyIntroduceLookupExpression(final String initialName, + final LinkedHashSet names, + final PsiNamedElement elementToRename, + final boolean shouldSelectAll, + final String advertisementText) { + super(initialName, names, elementToRename, shouldSelectAll, advertisementText); + myPointer = SmartPointerManager.getInstance(elementToRename.getProject()).createSmartPsiElementPointer(elementToRename); + } + + @Override + public LookupElement[] calculateLookupItems(ExpressionContext context) { + return createLookupItems(myName, context.getEditor(), getElement()); + } + + @Nullable + public PsiNamedElement getElement() { + return myPointer.getElement(); + } + + @Nullable + private LookupElement[] createLookupItems(String name, Editor editor, PsiNamedElement psiVariable) { + TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); + if (psiVariable != null) { + final TextResult insertedValue = + templateState != null ? templateState.getVariableValue(PRIMARY_VARIABLE_NAME) : null; + if (insertedValue != null) { + final String text = insertedValue.getText(); + if (!text.isEmpty() && !Comparing.strEqual(text, name)) { + final LinkedHashSet names = new LinkedHashSet(); + names.add(text); + for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) { + final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(psiVariable, psiVariable, names); + if (suggestedNameInfo != null && + provider instanceof PreferrableNameSuggestionProvider && + !((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) { + break; + } + } + final LookupElement[] items = new LookupElement[names.size()]; + final Iterator iterator = names.iterator(); + for (int i = 0; i < items.length; i++) { + items[i] = LookupElementBuilder.create(iterator.next()); + } + return items; + } + } + } + return myLookupItems; + } + } } 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 18a203b7ca82..79da56a63b2e 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 @@ -15,13 +15,9 @@ */ package com.intellij.refactoring.rename.inplace; -import com.intellij.codeInsight.completion.InsertHandler; -import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl; import com.intellij.codeInsight.highlighting.HighlightManager; -import com.intellij.codeInsight.lookup.LookupElement; -import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.codeInsight.template.*; @@ -43,7 +39,6 @@ import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; -import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; @@ -60,7 +55,6 @@ import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; -import com.intellij.psi.codeStyle.SuggestedNameInfo; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.ProjectScope; @@ -68,8 +62,6 @@ import com.intellij.psi.search.PsiSearchHelper; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.refactoring.rename.NameSuggestionProvider; -import com.intellij.refactoring.rename.PreferrableNameSuggestionProvider; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.util.containers.Stack; import org.jetbrains.annotations.NonNls; @@ -93,7 +85,7 @@ public abstract class InplaceRefactoring { protected final Editor myEditor; protected final Project myProject; protected RangeMarker myRenameOffset; - private String myAdvertisementText; + protected String myAdvertisementText; private ArrayList myHighlighters; protected String myInitialName; protected final String myOldName; @@ -205,7 +197,9 @@ public abstract class InplaceRefactoring { protected abstract boolean shouldSelectAll(); - protected abstract LookupElement[] createLookupItems(LookupElement[] lookupItems, String name); + protected MyLookupExpression createLookupExpression() { + return new MyLookupExpression(getInitialName(), myNameSuggestions, myElementToRename, shouldSelectAll(), myAdvertisementText); + } protected Collection collectRefs(SearchScope referencesSearchScope) { return ReferencesSearch.search(myElementToRename, referencesSearchScope, false).findAll(); @@ -536,8 +530,7 @@ public abstract class InplaceRefactoring { int offset) { if (reference.getElement() == selectedElement && contains(reference.getRangeInElement().shiftRight(selectedElement.getTextRange().getStartOffset()), offset)) { - Expression expression = new MyExpression(getInitialName(), myNameSuggestions); - builder.replaceElement(reference, PRIMARY_VARIABLE_NAME, expression, true); + builder.replaceElement(reference, PRIMARY_VARIABLE_NAME, createLookupExpression(), true); } else { builder.replaceElement(reference, OTHER_VARIABLE_NAME, PRIMARY_VARIABLE_NAME, false); @@ -555,8 +548,7 @@ public abstract class InplaceRefactoring { final PsiElement selectedElement, final TemplateBuilderImpl builder) { if (element == selectedElement) { - Expression expression = new MyExpression(getInitialName(), myNameSuggestions); - builder.replaceElement(element, PRIMARY_VARIABLE_NAME, expression, true); + builder.replaceElement(element, PRIMARY_VARIABLE_NAME, createLookupExpression(), true); } else if (textRange != null) { builder.replaceElement(element, textRange, OTHER_VARIABLE_NAME, PRIMARY_VARIABLE_NAME, false); @@ -614,63 +606,6 @@ public abstract class InplaceRefactoring { return range.getStartOffset() <= offset && offset <= range.getEndOffset(); } - protected class MyExpression extends Expression { - private final String myName; - private final LookupElement[] myLookupItems; - - protected MyExpression(String name, LinkedHashSet names) { - myName = name; - if (names == null) { - names = new LinkedHashSet(); - for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) { - final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(myElementToRename, myElementToRename, names); - if (suggestedNameInfo != null && provider instanceof PreferrableNameSuggestionProvider && !((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) break; - } - } - myLookupItems = new LookupElement[names.size()]; - final Iterator iterator = names.iterator(); - for (int i = 0; i < myLookupItems.length; i++) { - final String suggestion = iterator.next(); - myLookupItems[i] = LookupElementBuilder.create(suggestion).setInsertHandler(new InsertHandler() { - @Override - public void handleInsert(InsertionContext context, LookupElement item) { - if (shouldSelectAll()) return; - final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(myEditor); - final TemplateState templateState = TemplateManagerImpl.getTemplateState(topLevelEditor); - if (templateState != null) { - final TextRange range = templateState.getCurrentVariableRange(); - if (range != null) { - topLevelEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), suggestion); - } - } - } - }); - } - } - - public LookupElement[] calculateLookupItems(ExpressionContext context) { - return createLookupItems(myLookupItems, myName); - } - - public Result calculateQuickResult(ExpressionContext context) { - return calculateResult(context); - } - - public Result calculateResult(ExpressionContext context) { - TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); - final TextResult insertedValue = templateState != null ? templateState.getVariableValue(PRIMARY_VARIABLE_NAME) : null; - if (insertedValue != null) { - if (!insertedValue.getText().isEmpty()) return insertedValue; - } - return new TextResult(myName); - } - - @Override - public String getAdvertisingText() { - return myAdvertisementText; - } - } - private abstract class MyTemplateListener extends TemplateEditingAdapter { protected abstract void restoreDaemonUpdateState(); diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenameHandler.java b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenameHandler.java index 77c672dde956..216165ab7fcc 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenameHandler.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenameHandler.java @@ -16,15 +16,19 @@ package com.intellij.refactoring.rename.inplace; import com.intellij.codeInsight.lookup.LookupManager; +import com.intellij.codeInsight.template.impl.TemplateManagerImpl; +import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.lang.LanguageRefactoringSupport; import com.intellij.lang.refactoring.RefactoringSupportProvider; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.command.impl.StartMarkAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.Pass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiNameIdentifierOwner; import com.intellij.psi.PsiNamedElement; +import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.rename.RenamePsiElementProcessor; import org.jetbrains.annotations.NotNull; @@ -52,17 +56,29 @@ public class MemberInplaceRenameHandler extends VariableInplaceRenameHandler { if (elementToRename instanceof PsiNameIdentifierOwner) { final RenamePsiElementProcessor processor = RenamePsiElementProcessor.forElement(elementToRename); if (processor.isInplaceRenameSupported()) { - processor.substituteElementToRename(elementToRename, editor, new Pass() { - @Override - public void pass(PsiElement element) { - final MemberInplaceRenamer renamer = new MemberInplaceRenamer((PsiNameIdentifierOwner)elementToRename, element, editor); - boolean startedRename = renamer.performInplaceRename(); - if (!startedRename) { - performDialogRename(elementToRename, editor, dataContext); + final StartMarkAction startMarkAction = StartMarkAction.canStart(elementToRename.getProject()); + if (startMarkAction == null) { + processor.substituteElementToRename(elementToRename, editor, new Pass() { + @Override + public void pass(PsiElement element) { + final MemberInplaceRenamer renamer = new MemberInplaceRenamer((PsiNameIdentifierOwner)elementToRename, element, editor); + boolean startedRename = renamer.performInplaceRename(); + if (!startedRename) { + performDialogRename(elementToRename, editor, dataContext); + } + } + }); + return null; + } + else { + final InplaceRefactoring inplaceRefactoring = editor.getUserData(InplaceRefactoring.INPLACE_RENAMER); + if (inplaceRefactoring != null && inplaceRefactoring.getClass() == MemberInplaceRenamer.class) { + final TemplateState templateState = TemplateManagerImpl.getTemplateState(InjectedLanguageUtil.getTopLevelEditor(editor)); + if (templateState != null) { + templateState.gotoEnd(true); } } - }); - return null; + } } } performDialogRename(elementToRename, editor, dataContext); diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenamer.java b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenamer.java index b9520b91474e..642a03d542ec 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenamer.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenamer.java @@ -233,12 +233,9 @@ public class MemberInplaceRenamer extends VariableInplaceRenamer { } @Override - public void finish(boolean success) { - super.finish(success); - if (success) { - ((EditorImpl)InjectedLanguageUtil.getTopLevelEditor(myEditor)).startDumb(); - revertState(); - } + protected void revertStateOnFinish() { + ((EditorImpl)InjectedLanguageUtil.getTopLevelEditor(myEditor)).startDumb(); + revertState(); } @Nullable diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MyLookupExpression.java b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MyLookupExpression.java new file mode 100644 index 000000000000..4040e569fb5e --- /dev/null +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MyLookupExpression.java @@ -0,0 +1,116 @@ +/* + * 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.rename.inplace; + +import com.intellij.codeInsight.completion.InsertHandler; +import com.intellij.codeInsight.completion.InsertionContext; +import com.intellij.codeInsight.lookup.LookupElement; +import com.intellij.codeInsight.lookup.LookupElementBuilder; +import com.intellij.codeInsight.template.Expression; +import com.intellij.codeInsight.template.ExpressionContext; +import com.intellij.codeInsight.template.Result; +import com.intellij.codeInsight.template.TextResult; +import com.intellij.codeInsight.template.impl.TemplateManagerImpl; +import com.intellij.codeInsight.template.impl.TemplateState; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.extensions.Extensions; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiNamedElement; +import com.intellij.psi.codeStyle.SuggestedNameInfo; +import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; +import com.intellij.refactoring.rename.NameSuggestionProvider; +import com.intellij.refactoring.rename.PreferrableNameSuggestionProvider; + +import java.util.Iterator; +import java.util.LinkedHashSet; + +/** +* User: anna +* Date: 3/16/12 +*/ +public class MyLookupExpression extends Expression { + protected final String myName; + protected final LookupElement[] myLookupItems; + private final String myAdvertisementText; + + public MyLookupExpression(final String name, + final LinkedHashSet names, + final PsiNamedElement elementToRename, + final boolean shouldSelectAll, + final String advertisement) { + myName = name; + myAdvertisementText = advertisement; + myLookupItems = initLookupItems(names, elementToRename, shouldSelectAll); + } + + private static LookupElement[] initLookupItems(LinkedHashSet names, + PsiNamedElement elementToRename, + final boolean shouldSelectAll) { + if (names == null) { + names = new LinkedHashSet(); + for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) { + final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(elementToRename, elementToRename, names); + if (suggestedNameInfo != null && + provider instanceof PreferrableNameSuggestionProvider && + !((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) { + break; + } + } + } + final LookupElement[] lookupElements = new LookupElement[names.size()]; + final Iterator iterator = names.iterator(); + for (int i = 0; i < lookupElements.length; i++) { + final String suggestion = iterator.next(); + lookupElements[i] = LookupElementBuilder.create(suggestion).setInsertHandler(new InsertHandler() { + @Override + public void handleInsert(InsertionContext context, LookupElement item) { + if (shouldSelectAll) return; + final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(context.getEditor()); + final TemplateState templateState = TemplateManagerImpl.getTemplateState(topLevelEditor); + if (templateState != null) { + final TextRange range = templateState.getCurrentVariableRange(); + if (range != null) { + topLevelEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), suggestion); + } + } + } + }); + } + return lookupElements; + } + + public LookupElement[] calculateLookupItems(ExpressionContext context) { + return myLookupItems; + } + + public Result calculateQuickResult(ExpressionContext context) { + return calculateResult(context); + } + + public Result calculateResult(ExpressionContext context) { + TemplateState templateState = TemplateManagerImpl.getTemplateState(context.getEditor()); + final TextResult insertedValue = templateState != null ? templateState.getVariableValue(InplaceRefactoring.PRIMARY_VARIABLE_NAME) : null; + if (insertedValue != null) { + if (!insertedValue.getText().isEmpty()) return insertedValue; + } + return new TextResult(myName); + } + + @Override + public String getAdvertisingText() { + return myAdvertisementText; + } +} 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 2a24a63d929b..07f757cde272 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 @@ -15,7 +15,6 @@ */ package com.intellij.refactoring.rename.inplace; -import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.lang.Language; import com.intellij.lang.LanguageExtension; import com.intellij.lang.LanguageNamesValidation; @@ -192,6 +191,9 @@ public class VariableInplaceRenamer extends InplaceRefactoring { protected void performRefactoringRename(final String newName, final StartMarkAction markAction) { try { + if (!isIdentifier(newName)) { + return; + } PsiNamedElement elementToRename = getVariable(); if (elementToRename != null) { new WriteCommandAction(myProject, getCommandName()) { @@ -288,14 +290,26 @@ public class VariableInplaceRenamer extends InplaceRefactoring { return bind; } + @Override + public void finish(boolean success) { + super.finish(success); + if (success) { + revertStateOnFinish(); + } + else { + ((EditorImpl)InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumb(); + } + } + + protected void revertStateOnFinish() { + if (!isIdentifier(myInsertedName)) { + revertState(); + } + } + private boolean isIdentifier(final String newName) { final NamesValidator namesValidator = LanguageNamesValidation.INSTANCE.forLanguage(myLanguage); return namesValidator == null || namesValidator.isIdentifier(newName, myProject); } - - @Override - protected LookupElement[] createLookupItems(final LookupElement[] lookupItems, final String name) { - return lookupItems; - } } diff --git a/platform/lang-impl/src/com/intellij/util/indexing/ChangeTrackingValueContainer.java b/platform/lang-impl/src/com/intellij/util/indexing/ChangeTrackingValueContainer.java index 9b27c2696318..9dee34b26342 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/ChangeTrackingValueContainer.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/ChangeTrackingValueContainer.java @@ -139,9 +139,9 @@ class ChangeTrackingValueContainer extends UpdatableValueContainer final ValueContainerImpl newMerged; if (fromDisk instanceof ValueContainerImpl) { - newMerged = ((ValueContainerImpl)fromDisk).clone(); + newMerged = ((ValueContainerImpl)fromDisk).copy(); } else { - newMerged = ((ChangeTrackingValueContainer)fromDisk).getMergedData().clone(); + newMerged = ((ChangeTrackingValueContainer)fromDisk).getMergedData().copy(); } myInvalidated.forEach(new TIntProcedure() { @Override diff --git a/platform/lang-impl/src/com/intellij/util/indexing/ValueContainerImpl.java b/platform/lang-impl/src/com/intellij/util/indexing/ValueContainerImpl.java index 249a2b096d3d..0f1c63ff9b01 100644 --- a/platform/lang-impl/src/com/intellij/util/indexing/ValueContainerImpl.java +++ b/platform/lang-impl/src/com/intellij/util/indexing/ValueContainerImpl.java @@ -234,6 +234,22 @@ class ValueContainerImpl extends UpdatableValueContainer implement } }; + public ValueContainerImpl copy() { + final ValueContainerImpl container = new ValueContainerImpl(); + myInputIdMapping.forEachEntry(new TObjectObjectProcedure() { + @Override + public boolean execute(Value key, Object val) { + if (val instanceof TIntHashSet) { + container.myInputIdMapping.put(key, ((TIntHashSet)val).clone()); + } else { + container.myInputIdMapping.put(key, val); + } + return true; + } + }); + return container; + } + private static class SingleValueIterator implements IntIterator { private final int myValue; private boolean myValueRead = false; diff --git a/platform/platform-api/src/com/intellij/ide/ui/UISettings.java b/platform/platform-api/src/com/intellij/ide/ui/UISettings.java index 00facabfd373..5cc315a820c1 100644 --- a/platform/platform-api/src/com/intellij/ide/ui/UISettings.java +++ b/platform/platform-api/src/com/intellij/ide/ui/UISettings.java @@ -28,7 +28,6 @@ import com.intellij.openapi.components.Storage; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SystemInfo; import com.intellij.util.PlatformUtils; -import com.intellij.util.ui.GraphicsUtil; import com.intellij.util.xmlb.Accessor; import com.intellij.util.xmlb.SerializationFilter; import com.intellij.util.xmlb.XmlSerializerUtil; @@ -300,7 +299,25 @@ public class UISettings implements PersistentStateComponent, Exporta UISettings uiSettings=getInstance(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_OFF); - GraphicsUtil.setupAntialiasing(g2d, uiSettings == null || uiSettings.ANTIALIASING_IN_EDITOR, true); + if (uiSettings == null || uiSettings.ANTIALIASING_IN_EDITOR) { + Toolkit tk = Toolkit.getDefaultToolkit(); + //noinspection HardCodedStringLiteral + Map map = (Map)tk.getDesktopProperty("awt.font.desktophints"); + if (map != null) { + if (isRemoteDesktopConnected()) { + g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT); + } + else { + g2d.addRenderingHints(map); + } + } + else { + g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + } + } + else { + g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); + } } /** diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionButtonComponent.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionButtonComponent.java index 5d7e953929c1..6800cff6fae0 100644 --- a/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionButtonComponent.java +++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionButtonComponent.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. @@ -15,12 +15,18 @@ */ package com.intellij.openapi.actionSystem; +import org.intellij.lang.annotations.MagicConstant; + public interface ActionButtonComponent { int NORMAL = 0; int POPPED = 1; int PUSHED = -1; int SELECTED = 2; + @MagicConstant(flags = {NORMAL, POPPED, PUSHED, SELECTED}) + @interface ButtonState { } + + @ButtonState int getPopState(); int getWidth(); diff --git a/platform/platform-api/src/com/intellij/openapi/vfs/pointers/VirtualFilePointerListener.java b/platform/platform-api/src/com/intellij/openapi/vfs/pointers/VirtualFilePointerListener.java index 307889aa1a48..54086e008525 100644 --- a/platform/platform-api/src/com/intellij/openapi/vfs/pointers/VirtualFilePointerListener.java +++ b/platform/platform-api/src/com/intellij/openapi/vfs/pointers/VirtualFilePointerListener.java @@ -16,10 +16,11 @@ package com.intellij.openapi.vfs.pointers; import com.intellij.util.messages.Topic; +import org.jetbrains.annotations.NotNull; public interface VirtualFilePointerListener { Topic TOPIC = Topic.create("VirtualFilePointer", VirtualFilePointerListener.class); - void beforeValidityChanged(VirtualFilePointer[] pointers); - void validityChanged(VirtualFilePointer[] pointers); + void beforeValidityChanged(@NotNull VirtualFilePointer[] pointers); + void validityChanged(@NotNull VirtualFilePointer[] pointers); } diff --git a/platform/platform-api/src/com/intellij/ui/components/JBOptionButton.java b/platform/platform-api/src/com/intellij/ui/components/JBOptionButton.java index 6bf175f262c5..4acee12346c8 100644 --- a/platform/platform-api/src/com/intellij/ui/components/JBOptionButton.java +++ b/platform/platform-api/src/com/intellij/ui/components/JBOptionButton.java @@ -53,11 +53,7 @@ public class JBOptionButton extends JButton implements MouseMotionListener { private boolean myOkToProcessDefaultMnemonics = true; private IdeGlassPane myGlassPane; - private final Disposable myDisposable = new Disposable() { - @Override - public void dispose() { - } - }; + private final Disposable myDisposable = Disposer.newDisposable(); public JBOptionButton(Action action, Action[] options) { super(action); diff --git a/platform/platform-api/src/com/intellij/ui/switcher/SwitchingSession.java b/platform/platform-api/src/com/intellij/ui/switcher/SwitchingSession.java index 43472818b02c..0f5045843532 100644 --- a/platform/platform-api/src/com/intellij/ui/switcher/SwitchingSession.java +++ b/platform/platform-api/src/com/intellij/ui/switcher/SwitchingSession.java @@ -76,11 +76,7 @@ public class SwitchingSession implements KeyEventDispatcher, Disposable { }; private boolean myFadingAway; - private Disposable myPainterDisposable = new Disposable() { - @Override - public void dispose() { - } - }; + private Disposable myPainterDisposable = Disposer.newDisposable(); public SwitchingSession(SwitchManager mgr, SwitchProvider provider, KeyEvent e, @Nullable SwitchTarget preselected, boolean showSpots) { myManager = mgr; diff --git a/platform/platform-api/src/com/intellij/util/PathUtil.java b/platform/platform-api/src/com/intellij/util/PathUtil.java index fb5622bf0fa4..ad6e376ddb67 100644 --- a/platform/platform-api/src/com/intellij/util/PathUtil.java +++ b/platform/platform-api/src/com/intellij/util/PathUtil.java @@ -25,8 +25,6 @@ import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.File; - public class PathUtil { private PathUtil() { } @@ -63,8 +61,9 @@ public class PathUtil { @NotNull public static String getJarPathForClass(@NotNull Class aClass) { - String resourceRoot = PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class"); - return new File(resourceRoot).getAbsoluteFile().getAbsolutePath(); + final String pathForClass = PathManager.getJarPathForClass(aClass); + assert pathForClass != null : aClass; + return pathForClass; } @NotNull diff --git a/platform/platform-impl/src/com/intellij/help/impl/IdeaJHelp.java b/platform/platform-impl/src/com/intellij/help/impl/IdeaJHelp.java index 23eb1d1cd145..f09a39e97cb6 100644 --- a/platform/platform-impl/src/com/intellij/help/impl/IdeaJHelp.java +++ b/platform/platform-impl/src/com/intellij/help/impl/IdeaJHelp.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. @@ -15,7 +15,7 @@ */ package com.intellij.help.impl; -import com.intellij.ide.ui.UISettings; +import com.intellij.util.ui.GraphicsUtil; import javax.help.DefaultHelpModel; import javax.help.HelpSet; @@ -53,7 +53,7 @@ class IdeaJHelp extends JHelp{ @Override public void paint(Graphics g) { - UISettings.setupAntialiasing(g); + GraphicsUtil.setupAntialiasing(g); super.paint(g); } } \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/ActionInstallPlugin.java b/platform/platform-impl/src/com/intellij/ide/plugins/ActionInstallPlugin.java index bd9da284bc63..5bcda3846d13 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/ActionInstallPlugin.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/ActionInstallPlugin.java @@ -47,6 +47,8 @@ import java.util.*; public class ActionInstallPlugin extends AnAction implements DumbAware { final private static String updateMessage = IdeBundle.message("action.update.plugin"); + private static final Set ourInstallingNodes = new HashSet(); + private final PluginManagerMain installed; private final PluginManagerMain host; @@ -65,6 +67,7 @@ public class ActionInstallPlugin extends AnAction implements DumbAware { for (IdeaPluginDescriptor descr : selection) { presentation.setText(IdeBundle.message("action.download.and.install.plugin")); presentation.setDescription(IdeBundle.message("action.download.and.install.plugin")); + enabled &= !ourInstallingNodes.contains(descr); if (descr instanceof PluginNode) { enabled &= !PluginManagerColumnInfo.isDownloaded((PluginNode)descr); if (((PluginNode)descr).getStatus() == PluginNode.STATUS_INSTALLED) { @@ -108,6 +111,7 @@ public class ActionInstallPlugin extends AnAction implements DumbAware { if (pluginNode != null) { list.add(pluginNode); + ourInstallingNodes.add(pluginNode); } } try { @@ -143,7 +147,12 @@ public class ActionInstallPlugin extends AnAction implements DumbAware { } } }; - PluginManagerMain.downloadPlugins(list, host.getPluginsModel().view, onInstallRunnable); + PluginManagerMain.downloadPlugins(list, host.getPluginsModel().view, onInstallRunnable, new Runnable(){ + @Override + public void run() { + ourInstallingNodes.removeAll(list); + } + }); } catch (IOException e1) { PluginManagerMain.LOG.error(e1); diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java b/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java index 501075d8bf51..446cecb77a0c 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/InstalledPluginsManagerMain.java @@ -116,7 +116,9 @@ public class InstalledPluginsManagerMain extends PluginManagerMain { final Set notInstalled = new HashSet(); final Set disabledIds = new HashSet(); final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds(); + final PluginId[] optionalDependentPluginIds = pluginDescriptor.getOptionalDependentPluginIds(); for (PluginId id : dependentPluginIds) { + if (Arrays.binarySearch(optionalDependentPluginIds, id) > -1) continue; final boolean disabled = ((InstalledPluginsTableModel)pluginsModel).isDisabled(id); final boolean enabled = ((InstalledPluginsTableModel)pluginsModel).isEnabled(id); if (!enabled && !disabled && !PluginManager.isModuleDependency(id)) { diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java index ab722f4b8754..18f873d2c270 100644 --- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java +++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java @@ -288,7 +288,10 @@ public abstract class PluginManagerMain implements Disposable { loadPluginsFromHostInBackground(); } - public static boolean downloadPlugins(final List plugins, final List allPlugins, final Runnable onSuccess) throws IOException { + public static boolean downloadPlugins(final List plugins, + final List allPlugins, + final Runnable onSuccess, + final Runnable cleanup) throws IOException { final boolean[] result = new boolean[1]; try { ProgressManager.getInstance().run(new Task.Backgroundable(null, IdeBundle.message("progress.download.plugins"), true) { @@ -299,6 +302,18 @@ public abstract class PluginManagerMain implements Disposable { result[0] = true; } } + + @Override + public void onCancel() { + cleanup.run(); + super.onCancel(); + } + + @Override + public void onSuccess() { + super.onSuccess(); + cleanup.run(); + } }); } catch (RuntimeException e) { diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/ActionButtonLook.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/ActionButtonLook.java index 35334d3184fc..08c911e77c7f 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/ActionButtonLook.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/ActionButtonLook.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. @@ -32,12 +32,14 @@ public abstract class ActionButtonLook { paintBorder(g, button, getState(button)); } - public abstract void paintBackground(Graphics g, JComponent component, int state); + public abstract void paintBackground(Graphics g, JComponent component, @ActionButtonComponent.ButtonState int state); - public abstract void paintBorder(Graphics g, JComponent component, int state); + public abstract void paintBorder(Graphics g, JComponent component, @ActionButtonComponent.ButtonState int state); - protected int getState(ActionButtonComponent button) { // Do NOT inline this method. - // Because of compiler bug upcast from ButtonType to ActionButtonComponent is important + @SuppressWarnings("MethodMayBeStatic") + @ActionButtonComponent.ButtonState + protected int getState(ActionButtonComponent button) { + // DO NOT inline this method! Because of compiler bug up-cast from ButtonType to ActionButtonComponent is important! return button.getPopState(); } diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/IdeaActionButtonLook.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/IdeaActionButtonLook.java index c65146fcaa8f..730b5cd35e66 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/IdeaActionButtonLook.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/IdeaActionButtonLook.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. @@ -27,39 +27,36 @@ import java.awt.*; * @author max */ public class IdeaActionButtonLook extends ActionButtonLook { + private static final Color ALPHA_20 = new Color(0, 0, 0, 20); + private static final Color ALPHA_30 = new Color(0, 0, 0, 30); + private static final Color ALPHA_40 = new Color(0, 0, 0, 40); + private static final Color ALPHA_120 = new Color(0, 0, 0, 120); + private static final BasicStroke BASIC_STROKE = new BasicStroke(); + public void paintBackground(Graphics g, JComponent component, int state) { + if (state == ActionButtonComponent.NORMAL) return; Dimension dimension = component.getSize(); - if (state != ActionButtonComponent.NORMAL) { - if (!UIUtil.isUnderAquaLookAndFeel()) { - if (state == ActionButtonComponent.POPPED) { - g.setColor(new Color(181, 190, 214)); - g.fillRect(0, 0, dimension.width, dimension.height); - } - else { - g.setColor(new Color(130, 146, 185)); - g.fillRect(0, 0, dimension.width, dimension.height); - } - } else if (state == ActionButtonComponent.POPPED) { + + if (UIUtil.isUnderAquaLookAndFeel()) { + if (state == ActionButtonComponent.PUSHED) { + ((Graphics2D)g).setPaint(new GradientPaint(0, 0, ALPHA_40, dimension.width, dimension.height, ALPHA_20)); + g.fillRect(0, 0, dimension.width - 1, dimension.height - 1); + + g.setColor(ALPHA_120); + g.drawLine(0, 0, 0, dimension.height - 2); + g.drawLine(1, 0, dimension.width - 2, 0); + + g.setColor(ALPHA_30); + g.drawRect(1, 1, dimension.width - 3, dimension.height - 3); + } + else if (state == ActionButtonComponent.POPPED) { ((Graphics2D)g).setPaint(new GradientPaint(0, 0, Gray._235, 0, dimension.height, Gray._200)); g.fillRect(1, 1, dimension.width - 3, dimension.height - 3); } } - if (state == ActionButtonComponent.PUSHED) { - if (UIUtil.isUnderAquaLookAndFeel()) { - ((Graphics2D)g).setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 40), dimension.width, dimension.height, new Color(0, 0, 0, 20))); - g.fillRect(0, 0, dimension.width - 1, dimension.height - 1); - - g.setColor(new Color(0, 0, 0, 120)); - g.drawLine(0, 0, 0, dimension.height - 2); - g.drawLine(1, 0, dimension.width - 2, 0); - - g.setColor(new Color(0, 0, 0, 30)); - g.drawRect(1, 1, dimension.width - 3, dimension.height - 3); - } - else { - g.setColor(new Color(130, 146, 185)); - g.fillRect(0, 0, dimension.width, dimension.height); - } + else { + g.setColor(state == ActionButtonComponent.PUSHED ? UIUtil.getPanelBackground().darker() : ALPHA_40); + g.fillRect(1, 1, dimension.width - 2, dimension.height - 2); } } @@ -69,18 +66,14 @@ public class IdeaActionButtonLook extends ActionButtonLook { if (UIUtil.isUnderAquaLookAndFeel()) { if (state == ActionButtonComponent.POPPED) { - g.setColor(new Color(0, 0, 0, 30)); + g.setColor(ALPHA_30); g.drawRoundRect(r.x, r.y, r.width - 2, r.height - 2, 4, 4); } - } else { - Color color = new Color(8, 36, 107); - g.setColor(color); - UIUtil.drawLine(g, r.x, r.y, r.x, (r.y + r.height) - 1); - UIUtil.drawLine(g, r.x, r.y, (r.x + r.width) - 1, r.y); - UIUtil.drawLine(g, (r.x + r.width) - 1, r.y, (r.x + r.width) - 1, - (r.y + r.height) - 1); - UIUtil.drawLine(g, r.x, (r.y + r.height) - 1, (r.x + r.width) - 1, - (r.y + r.height) - 1); + } + else { + g.setColor(UIUtil.getPanelBackground().darker().darker()); + ((Graphics2D)g).setStroke(BASIC_STROKE); + g.drawRoundRect(r.x, r.y, r.width - 2, r.height - 2, 4, 4); } } @@ -93,10 +86,6 @@ public class IdeaActionButtonLook extends ActionButtonLook { } public void paintIconAt(Graphics g, ActionButtonComponent button, Icon icon, int x, int y) { - if (button.getPopState() == ActionButtonComponent.PUSHED && !UIUtil.isUnderAquaLookAndFeel()) { - x++; - y++; - } icon.paintIcon(null, g, x, y); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/InplaceActionButtonLook.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/InplaceActionButtonLook.java index 3dad6ce02135..6ff31ab169d3 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/InplaceActionButtonLook.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/InplaceActionButtonLook.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. @@ -15,12 +15,10 @@ */ package com.intellij.openapi.actionSystem.impl; - import javax.swing.*; import java.awt.*; public class InplaceActionButtonLook extends IdeaActionButtonLook { - @Override public void paintBackground(Graphics g, JComponent component, int state) { } @@ -28,5 +26,4 @@ public class InplaceActionButtonLook extends IdeaActionButtonLook { @Override public void paintBorder(Graphics g, JComponent component, int state) { } - } diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/StartMarkAction.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/StartMarkAction.java index 159c28edb6d0..26bb6593e322 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/StartMarkAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/StartMarkAction.java @@ -88,6 +88,10 @@ public class StartMarkAction extends BasicUndoableAction { return markAction; } + public static StartMarkAction canStart(Project project) { + return ourCurrentMarks.get(project); + } + static void markFinished(Project project) { final StartMarkAction existingMark = ourCurrentMarks.remove(project); if (existingMark != null) { diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackRunner.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackRunner.java index 7a9cbb076fb2..bc25865c8866 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackRunner.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/PlaybackRunner.java @@ -66,11 +66,7 @@ public class PlaybackRunner { private Map myRegistryValues = new HashMap(); - private Disposable myOnStop = new Disposable() { - @Override - public void dispose() { - } - }; + private Disposable myOnStop = Disposer.newDisposable(); public PlaybackRunner(String script, StatusCallback callback, final boolean useDirectActionCall, boolean stopOnAppDeactivation, boolean useTypingTargets) { myScript = script; diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/EditorPlaybackCall.java b/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/EditorPlaybackCall.java index f981a98531a4..16f67a1df549 100644 --- a/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/EditorPlaybackCall.java +++ b/platform/platform-impl/src/com/intellij/openapi/ui/playback/util/EditorPlaybackCall.java @@ -66,11 +66,7 @@ public class EditorPlaybackCall { public static AsyncResult waitDaemonForFinish(final PlaybackContext context) { final AsyncResult result = new AsyncResult(); - final Disposable connection = new Disposable() { - @Override - public void dispose() { - } - }; + final Disposable connection = Disposer.newDisposable(); result.doWhenProcessed(new Runnable() { @Override public void run() { diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java index 75a7c922e459..5c91df5975d4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java @@ -29,7 +29,6 @@ import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.BuildNumber; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.VirtualFileSystem; @@ -151,13 +150,13 @@ public class PluginDownloader { return true; } - public static void replaceLib(String libPath, String libName, VirtualFile fromFile) throws IOException { + public static void replaceLib(String libPath, String libName, File fromFile) throws IOException { final File source = new File(libPath, libName); StartupActionScriptManager.ActionCommand deleteOld = new StartupActionScriptManager.DeleteCommand(source); StartupActionScriptManager.addActionCommand(deleteOld); - StartupActionScriptManager.ActionCommand addNew = new StartupActionScriptManager.CopyCommand(VfsUtil.virtualToIoFile(fromFile), source); + StartupActionScriptManager.ActionCommand addNew = new StartupActionScriptManager.CopyCommand(fromFile, source); StartupActionScriptManager.addActionCommand(addNew); } @@ -329,8 +328,7 @@ public class PluginDownloader { if (fileName == null || !PathUtil.isValidFileName(fileName)) { FileUtil.delete(file); - LOG.warn("Invalid file name (header=" + contentDisposition + "; url=" + connection.getURL() + "; name=" + fileName + ")"); - throw new IOException("Invalid filename returned by the server"); + throw new IOException("Invalid filename returned by a server"); } return fileName; diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerContainerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerContainerImpl.java index ae746ef980e3..2c4fe1c3ac34 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerContainerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerContainerImpl.java @@ -272,6 +272,7 @@ public class VirtualFilePointerContainerImpl implements VirtualFilePointerContai return myVirtualFilePointerManager.duplicate(virtualFilePointer, myParent, myListener); } + @NonNls @Override public String toString() { return "VFPContainer: "+myList/*+"; parent:"+myParent*/; diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerImpl.java index fa98c84c896e..94958ea54446 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerImpl.java @@ -219,14 +219,7 @@ public class VirtualFilePointerImpl extends UserDataHolderBase implements Virtua disposed = true; final Pair pair = myFileAndUrl; - VirtualFile file = pair.first; - if (file != null) { - ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).clearPointerCaches(file.getUrl(), myListener); - } - String url = pair.second; - if (url != null && (file == null || !url.equals(file.getUrl()))) { - ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).clearPointerCaches(url, myListener); - } + ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).clearPointerCaches(pair.first, pair.second, myListener); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerManagerImpl.java index 6b9ac8d5ab93..afde58208c46 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/VirtualFilePointerManagerImpl.java @@ -52,7 +52,7 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp private final Set myContainers = new THashSet(TObjectHashingStrategy.IDENTITY); private final VirtualFileManagerEx myVirtualFileManager; private final MessageBus myBus; - private static final Comparator COMPARATOR = SystemInfo.isFileSystemCaseSensitive ? new Comparator() { + private static final Comparator URL_COMPARATOR = SystemInfo.isFileSystemCaseSensitive ? new Comparator() { @Override public int compare(@NotNull String url1, @NotNull String url2) { return url1.compareTo(url2); @@ -70,9 +70,18 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp bus.connect().subscribe(VirtualFileManager.VFS_CHANGES, new VFSEventsProcessor()); } - synchronized void clearPointerCaches(String url, VirtualFilePointerListener listener) { + synchronized void clearPointerCaches(VirtualFile file, String url, VirtualFilePointerListener listener) { + if (file != null) { + removeFromMap(file.getUrl(), listener); + } + if (url != null && (file == null || URL_COMPARATOR.compare(url, file.getUrl()) != 0)) { + removeFromMap(url, listener); + } + } + + private void removeFromMap(String url, VirtualFilePointerListener listener) { TreeMap urlToPointer = myUrlToPointerMaps.get(listener); - assert urlToPointer != null; + assert urlToPointer != null : url; urlToPointer.remove(VfsUtil.urlToPath(url)); if (urlToPointer.isEmpty()) { myUrlToPointerMaps.remove(listener); @@ -272,7 +281,7 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp private synchronized VirtualFilePointerImpl getOrCreate(VirtualFile file, @NotNull String url, Disposable parentDisposable, @Nullable VirtualFilePointerListener listener, String path) { TreeMap urlToPointer = myUrlToPointerMaps.get(listener); if (urlToPointer == null) { - urlToPointer = new TreeMap(COMPARATOR); + urlToPointer = new TreeMap(URL_COMPARATOR); myUrlToPointerMaps.put(listener, urlToPointer); } VirtualFilePointerImpl pointer = urlToPointer.get(path); @@ -309,7 +318,7 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp } /** - * Does nothing. To cleanup pointer correctly, just pass Disposable during its creation + * Does nothing. To cleanup the pointer correctly, pass Disposable to its constructor * @see #create(String, com.intellij.openapi.Disposable, com.intellij.openapi.vfs.pointers.VirtualFilePointerListener) */ @Override @@ -340,7 +349,7 @@ public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager imp synchronized (myContainers) { if (!myContainers.isEmpty()) { VirtualFilePointerContainerImpl container = myContainers.iterator().next(); - myContainers.clear(); + //myContainers.clear(); throw new RuntimeException("Not disposed container " + container); } } diff --git a/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java b/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java index ac2594533d34..5cec29164100 100644 --- a/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java +++ b/platform/platform-impl/src/com/intellij/ui/BalloonImpl.java @@ -696,6 +696,7 @@ public class BalloonImpl implements Balloon, IdeTooltip.Ui { } myVisible = false; + myTracker = null; } public void dispose() { diff --git a/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java b/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java index 9b51ccbd7359..24a3ebb4b1a1 100644 --- a/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java +++ b/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java @@ -58,7 +58,7 @@ public class MacMainFrameDecorator implements UISettingsListener, Disposable { try { Class.forName("com.apple.eawt.FullScreenUtilities"); HAS_FULLSCREEN_UTILITIES = true; - } catch (ClassNotFoundException e) { + } catch (Exception e) { HAS_FULLSCREEN_UTILITIES = false; } } diff --git a/platform/platform-impl/src/com/intellij/ui/popup/util/MnemonicsSearch.java b/platform/platform-impl/src/com/intellij/ui/popup/util/MnemonicsSearch.java index 0a985d8e1bcc..92005e006a2f 100644 --- a/platform/platform-impl/src/com/intellij/ui/popup/util/MnemonicsSearch.java +++ b/platform/platform-impl/src/com/intellij/ui/popup/util/MnemonicsSearch.java @@ -16,6 +16,7 @@ package com.intellij.ui.popup.util; import com.intellij.openapi.ui.popup.MnemonicNavigationFilter; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.popup.WizardPopup; import java.awt.event.KeyEvent; @@ -46,7 +47,7 @@ public abstract class MnemonicsSearch { } public void process(KeyEvent e) { - if (e.isConsumed()) return; + if (e.isConsumed() || !StringUtil.isEmptyOrSpaces(myPopup.getSpeedSearch().getFilter())) return; if (Character.isLetterOrDigit(e.getKeyChar())) { final String s = Character.toString(e.getKeyChar()); diff --git a/platform/platform-impl/src/com/intellij/util/ui/ChangesTrackingTableView.java b/platform/platform-impl/src/com/intellij/util/ui/ChangesTrackingTableView.java index 0b89e21798a6..d885ca83e60b 100644 --- a/platform/platform-impl/src/com/intellij/util/ui/ChangesTrackingTableView.java +++ b/platform/platform-impl/src/com/intellij/util/ui/ChangesTrackingTableView.java @@ -43,11 +43,7 @@ public abstract class ChangesTrackingTableView extends TableView { public boolean editCellAt(final int row, final int column, EventObject e) { if (super.editCellAt(row, column, e)) { assert myEditorListenerDisposable == null; - myEditorListenerDisposable = new Disposable() { - @Override - public void dispose() { - } - }; + myEditorListenerDisposable = Disposer.newDisposable(); addChangeListener(getEditorComponent(), new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/VirtualFilePointerTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/VirtualFilePointerTest.java index ec9f7b074671..fd28150311a2 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/vfs/VirtualFilePointerTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/vfs/VirtualFilePointerTest.java @@ -34,6 +34,7 @@ import com.intellij.util.Processor; import com.intellij.util.ThrowableRunnable; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; @@ -56,7 +57,7 @@ public class VirtualFilePointerTest extends PlatformLangTestCase { private final ArrayList myLog = new ArrayList(); @Override - public void beforeValidityChanged(VirtualFilePointer[] pointers) { + public void beforeValidityChanged(@NotNull VirtualFilePointer[] pointers) { verifyPointersInCorrectState(pointers); myLog.add(buildMessage("before", pointers)); } @@ -74,7 +75,7 @@ public class VirtualFilePointerTest extends PlatformLangTestCase { } @Override - public void validityChanged(VirtualFilePointer[] pointers) { + public void validityChanged(@NotNull VirtualFilePointer[] pointers) { verifyPointersInCorrectState(pointers); myLog.add(buildMessage("after", pointers)); } @@ -240,12 +241,12 @@ public class VirtualFilePointerTest extends PlatformLangTestCase { final VirtualFilePointer[] pointersToWatch = new VirtualFilePointer[2]; final VirtualFilePointerListener listener = new VirtualFilePointerListener() { @Override - public void beforeValidityChanged(VirtualFilePointer[] pointers) { + public void beforeValidityChanged(@NotNull VirtualFilePointer[] pointers) { verifyPointersInCorrectState(pointersToWatch); } @Override - public void validityChanged(VirtualFilePointer[] pointers) { + public void validityChanged(@NotNull VirtualFilePointer[] pointers) { verifyPointersInCorrectState(pointersToWatch); } }; @@ -302,12 +303,12 @@ public class VirtualFilePointerTest extends PlatformLangTestCase { final VirtualFilePointer[] pointersToWatch = new VirtualFilePointer[1]; final VirtualFilePointerListener listener = new VirtualFilePointerListener() { @Override - public void beforeValidityChanged(VirtualFilePointer[] pointers) { + public void beforeValidityChanged(@NotNull VirtualFilePointer[] pointers) { verifyPointersInCorrectState(pointersToWatch); } @Override - public void validityChanged(VirtualFilePointer[] pointers) { + public void validityChanged(@NotNull VirtualFilePointer[] pointers) { verifyPointersInCorrectState(pointersToWatch); } }; @@ -442,11 +443,11 @@ public class VirtualFilePointerTest extends PlatformLangTestCase { Disposable disposable = Disposer.newDisposable(); final VirtualFilePointer pointer = myVirtualFilePointerManager.create(vFile[0], disposable, new VirtualFilePointerListener() { @Override - public void beforeValidityChanged(VirtualFilePointer[] pointers) { + public void beforeValidityChanged(@NotNull VirtualFilePointer[] pointers) { } @Override - public void validityChanged(VirtualFilePointer[] pointers) { + public void validityChanged(@NotNull VirtualFilePointer[] pointers) { } }); diff --git a/platform/testFramework/src/com/intellij/testFramework/AbstractVcsTestCase.java b/platform/testFramework/src/com/intellij/testFramework/AbstractVcsTestCase.java index 57ed171e60bb..ebff18485708 100644 --- a/platform/testFramework/src/com/intellij/testFramework/AbstractVcsTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/AbstractVcsTestCase.java @@ -114,8 +114,11 @@ public abstract class AbstractVcsTestCase { } protected void setVcsMappings(VcsDirectoryMapping... mappings) { + setVcsMappings(Arrays.asList(mappings)); + } + protected void setVcsMappings(List mappings) { ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject); - vcsManager.setDirectoryMappings(Arrays.asList(mappings)); + vcsManager.setDirectoryMappings(mappings); vcsManager.updateActiveVcss(); } diff --git a/platform/usageView/src/com/intellij/usages/UsageModelTracker.java b/platform/usageView/src/com/intellij/usages/UsageModelTracker.java index 22271a4a220c..4fa69bbc6444 100644 --- a/platform/usageView/src/com/intellij/usages/UsageModelTracker.java +++ b/platform/usageView/src/com/intellij/usages/UsageModelTracker.java @@ -19,6 +19,7 @@ import com.intellij.openapi.Disposable; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.NotNull; import java.util.List; @@ -35,32 +36,32 @@ public class UsageModelTracker implements Disposable { public UsageModelTracker(Project project) { final PsiTreeChangeListener myPsiListener = new PsiTreeChangeAdapter() { @Override - public void childAdded(PsiTreeChangeEvent event) { + public void childAdded(@NotNull PsiTreeChangeEvent event) { doFire(event, false); } @Override - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { doFire(event, false); } @Override - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { doFire(event, false); } @Override - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { doFire(event, false); } @Override - public void childMoved(PsiTreeChangeEvent event) { + public void childMoved(@NotNull PsiTreeChangeEvent event) { doFire(event, false); } @Override - public void propertyChanged(PsiTreeChangeEvent event) { + public void propertyChanged(@NotNull PsiTreeChangeEvent event) { doFire(event, true); } }; diff --git a/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java b/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java index ff77c63af49c..2881afe12457 100644 --- a/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java +++ b/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java @@ -44,6 +44,90 @@ public class FileUtilRt { private static String ourCanonicalTempPathCache = null; + @NotNull + public static String getExtension(@NotNull String fileName) { + int index = fileName.lastIndexOf('.'); + if (index < 0) return ""; + return fileName.substring(index + 1).toLowerCase(); + } + + @NotNull + public static String toSystemDependentName(@NonNls @NotNull String aFileName) { + return aFileName.replace('/', File.separatorChar).replace('\\', File.separatorChar); + } + + @NotNull + public static String toSystemIndependentName(@NonNls @NotNull String aFileName) { + return aFileName.replace('\\', '/'); + } + + @Nullable + public static String getRelativePath(File base, File file) { + if (base == null || file == null) return null; + + if (!base.isDirectory()) { + base = base.getParentFile(); + if (base == null) return null; + } + + if (base.equals(file)) return "."; + + final String filePath = file.getAbsolutePath(); + String basePath = base.getAbsolutePath(); + return getRelativePath(basePath, filePath, File.separatorChar); + } + + @Nullable + public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator) { + return getRelativePath(basePath, filePath, separator, SystemInfoRt.isFileSystemCaseSensitive); + } + + @Nullable + public static String getRelativePath(@NotNull String basePath, + @NotNull String filePath, + final char separator, + final boolean caseSensitive) { + basePath = ensureEnds(basePath, separator); + + String basePathToCompare = caseSensitive ? basePath : basePath.toLowerCase(); + String filePathToCompare = caseSensitive ? filePath : filePath.toLowerCase(); + if (basePathToCompare.equals(ensureEnds(filePathToCompare, separator))) return "."; + int len = 0; + int lastSeparatorIndex = 0; // need this for cases like this: base="/temp/abcde/base" and file="/temp/ab" + while (len < filePath.length() && len < basePath.length() && filePathToCompare.charAt(len) == basePathToCompare.charAt(len)) { + if (basePath.charAt(len) == separator) { + lastSeparatorIndex = len; + } + len++; + } + + if (len == 0) return null; + + StringBuilder relativePath = new StringBuilder(); + for (int i = len; i < basePath.length(); i++) { + if (basePath.charAt(i) == separator) { + relativePath.append(".."); + relativePath.append(separator); + } + } + relativePath.append(filePath.substring(lastSeparatorIndex + 1)); + + return relativePath.toString(); + } + + private static String ensureEnds(@NotNull String s, final char endsWith) { + return StringUtilRt.endsWithChar(s, endsWith) ? s : s + endsWith; + } + + @NotNull + public static String getNameWithoutExtension(@NotNull String name) { + int i = name.lastIndexOf('.'); + if (i != -1) { + name = name.substring(0, i); + } + return name; + } + @NotNull public static File createTempDirectory(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { File file = doCreateTempFile(prefix, suffix); @@ -67,6 +151,7 @@ public class FileUtilRt { return createTempFile(dir, prefix, suffix, create, true); } + @NotNull public static File createTempFile(@NonNls final File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix, @@ -132,6 +217,7 @@ public class FileUtilRt { return SystemInfoRt.isWindows && canonical.getAbsolutePath().contains(" ") ? temp.getAbsoluteFile() : canonical; } + @NotNull public static String getTempDirectory() { if (ourCanonicalTempPathCache == null) { ourCanonicalTempPathCache = calcCanonicalTempPath(); @@ -267,5 +353,4 @@ public class FileUtilRt { } return bytes; } - } diff --git a/platform/util-rt/src/com/intellij/openapi/util/text/StringUtilRt.java b/platform/util-rt/src/com/intellij/openapi/util/text/StringUtilRt.java index 9b98436709b8..cd4fad48a19e 100644 --- a/platform/util-rt/src/com/intellij/openapi/util/text/StringUtilRt.java +++ b/platform/util-rt/src/com/intellij/openapi/util/text/StringUtilRt.java @@ -76,7 +76,9 @@ public class StringUtilRt { } @NotNull - public static String convertLineSeparators(@NotNull String text, @NotNull String newSeparator, @Nullable int[] offsetsToKeep, + public static String convertLineSeparators(@NotNull String text, + @NotNull String newSeparator, + @Nullable int[] offsetsToKeep, boolean keepCarriageReturn) { StringBuilder buffer = null; int intactLength = 0; @@ -184,4 +186,8 @@ public class StringUtilRt { } return fqName; } + + public static boolean endsWithChar(@Nullable CharSequence s, char suffix) { + return s != null && s.length() != 0 && s.charAt(s.length() - 1) == suffix; + } } diff --git a/platform/util/src/com/intellij/CommonBundle.java b/platform/util/src/com/intellij/CommonBundle.java index 941ce72fdd19..78801c719b6f 100644 --- a/platform/util/src/com/intellij/CommonBundle.java +++ b/platform/util/src/com/intellij/CommonBundle.java @@ -18,6 +18,7 @@ package com.intellij; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.PropertyKey; import java.lang.ref.Reference; @@ -27,6 +28,7 @@ import java.util.ResourceBundle; /** * @author yole */ +@SuppressWarnings("MethodOverridesStaticMethodOfSuperclass") public class CommonBundle extends BundleBase { public static boolean assertKeyIsFound = false; @@ -50,6 +52,18 @@ public class CommonBundle extends BundleBase { return bundle; } + public static String messageOrDefault(@Nullable final ResourceBundle bundle, + final String key, + @Nullable final String defaultValue, + final Object... params) { + return BundleBase.messageOrDefault(bundle, key, defaultValue, params); + } + + @NotNull + public static String message(@NotNull ResourceBundle bundle, @NotNull String key, @NotNull Object... params) { + return BundleBase.message(bundle, key, params); + } + @NotNull public static String getCancelButtonText() { return message("button.cancel"); diff --git a/platform/util/src/com/intellij/openapi/application/PathManager.java b/platform/util/src/com/intellij/openapi/application/PathManager.java index d9ef319b731f..78f45fe59910 100644 --- a/platform/util/src/com/intellij/openapi/application/PathManager.java +++ b/platform/util/src/com/intellij/openapi/application/PathManager.java @@ -16,23 +16,30 @@ package com.intellij.openapi.application; +import com.google.common.collect.Lists; +import com.intellij.CommonBundle; import com.intellij.openapi.util.NamedJDOMExternalizable; import com.intellij.openapi.util.SystemInfo; +import com.intellij.openapi.util.SystemInfoRt; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.SystemProperties; import com.intellij.util.io.URLUtil; +import com.sun.jna.TypeMapper; +import com.sun.jna.platform.FileUtils; +import gnu.trove.THashSet; +import org.apache.log4j.Appender; +import org.apache.oro.text.regex.PatternMatcher; +import org.jdom.Document; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; +import org.picocontainer.PicoContainer; import java.io.*; import java.net.URL; -import java.util.Enumeration; -import java.util.Properties; -import java.util.PropertyResourceBundle; -import java.util.Set; +import java.util.*; public class PathManager { @NonNls public static final String PROPERTIES_FILE = "idea.properties.file"; @@ -309,11 +316,12 @@ public class PathManager { /** * Attempts to extract classpath entry part from passed URL. */ + @Nullable @NonNls private static String extractRoot(URL resourceURL, String resourcePath) { if (!(StringUtil.startsWithChar(resourcePath, '/') || StringUtil.startsWithChar(resourcePath, '\\'))) { - //noinspection HardCodedStringLiteral - System.err.println("precondition failed: "+resourcePath); + //noinspection HardCodedStringLiteral,UseOfSystemOutOrSystemErr + System.err.println("precondition failed: " + resourcePath); return null; } String protocol = resourceURL.getProtocol(); @@ -338,8 +346,8 @@ public class PathManager { } } if (resultPath == null) { - //noinspection HardCodedStringLiteral - System.err.println("cannot extract: "+resultPath + " from "+resourceURL); + //noinspection HardCodedStringLiteral,UseOfSystemOutOrSystemErr + System.err.println("cannot extract: " + resultPath + " from " + resourceURL); return null; } @@ -362,45 +370,48 @@ public class PathManager { getHomePath() + "/community/bin/idea.properties"); if (propFile != null) { - InputStream fis = null; try { - fis = new BufferedInputStream(new FileInputStream(propFile)); - final PropertyResourceBundle bundle = new PropertyResourceBundle(fis); - final Enumeration keys = bundle.getKeys(); - String home = (String)bundle.handleGetObject("idea.home"); - if (home != null && ourHomePath == null) { - ourHomePath = getAbsolutePath(substitueVars(home)); - } - final Properties sysProperties = System.getProperties(); - while (keys.hasMoreElements()) { - String key = (String)keys.nextElement(); - if (sysProperties.getProperty(key, null) == null) { // load the property from the property file only if it is not defined yet - final String value = substitueVars(bundle.getString(key)); - sysProperties.setProperty(key, value); + InputStream fis = new BufferedInputStream(new FileInputStream(propFile)); + try { + final PropertyResourceBundle bundle = new PropertyResourceBundle(fis); + final Enumeration keys = bundle.getKeys(); + String home = (String)bundle.handleGetObject("idea.home"); + if (home != null && ourHomePath == null) { + ourHomePath = getAbsolutePath(substituteVars(home)); } + final Properties sysProperties = System.getProperties(); + while (keys.hasMoreElements()) { + String key = (String)keys.nextElement(); + if (sysProperties.getProperty(key, null) == null) { // load the property from the property file only if it is not defined yet + final String value = substituteVars(bundle.getString(key)); + sysProperties.setProperty(key, value); + } + } + } + finally{ + fis.close(); } } catch (IOException e) { - //noinspection HardCodedStringLiteral + //noinspection HardCodedStringLiteral,UseOfSystemOutOrSystemErr System.err.println("Problem reading from property file: " + propFile.getPath()); } - finally{ - try { - if (fis != null) { - fis.close(); - } - } - catch (IOException e) { - } - } } } + /** @deprecated use {@linkplain #substituteVars(String)} (to remove in IDEA 13) */ + @SuppressWarnings({"UnusedDeclaration", "ConstantConditions"}) public static String substitueVars(String s) { + return substituteVars(s); + } + + @Nullable + public static String substituteVars(String s) { final String ideaHomePath = getHomePath(); return substituteVars(s, ideaHomePath); } + @Nullable public static String substituteVars(String s, final String ideaHomePath) { if (s == null) return null; if (s.startsWith("..")) { @@ -435,4 +446,42 @@ public class PathManager { public static void cleanup() { ourPluginsPath = null; } + + @Nullable + public static String getJarPathForClass(@NotNull Class aClass) { + final String resourceRoot = getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class"); + return resourceRoot != null ? new File(resourceRoot).getAbsolutePath() : null; + } + + @NotNull + public static Collection getUtilClassPath() { + final List> classes = Arrays.asList( + PathManager.class, // module 'util' + NotNull.class, // module 'annotations' + SystemInfoRt.class, // module 'util-rt' + Document.class, // jDOM + Appender.class, // log4j + THashSet.class, // trove4j + PicoContainer.class, // PicoContainer + Lists.class, // guava + TypeMapper.class, // JNA + FileUtils.class, // JNA (jna-utils) + PatternMatcher.class // OROMatcher + ); + + final Set classPath = new HashSet(); + for (Class aClass : classes) { + final String path = getJarPathForClass(aClass); + if (path != null) { + classPath.add(path); + } + } + + final String resourceRoot = getResourceRoot(PathManager.class, "/messages/CommonBundle.properties"); // platform-resources-en + if (resourceRoot != null) { + classPath.add(new File(resourceRoot).getAbsolutePath()); + } + + return Collections.unmodifiableCollection(classPath); + } } diff --git a/platform/util/src/com/intellij/openapi/util/io/FileUtil.java b/platform/util/src/com/intellij/openapi/util/io/FileUtil.java index c21488878104..3123a0cc0255 100644 --- a/platform/util/src/com/intellij/openapi/util/io/FileUtil.java +++ b/platform/util/src/com/intellij/openapi/util/io/FileUtil.java @@ -34,6 +34,7 @@ import org.intellij.lang.annotations.RegExp; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.TestOnly; import java.io.*; import java.lang.reflect.Method; @@ -41,23 +42,15 @@ import java.nio.channels.FileChannel; import java.util.*; import java.util.regex.Pattern; -@SuppressWarnings({"UtilityClassWithoutPrivateConstructor"}) +@SuppressWarnings({"UtilityClassWithoutPrivateConstructor", "MethodOverridesStaticMethodOfSuperclass"}) public class FileUtil extends FileUtilRt { public static final int MEGABYTE = 1024 * 1024; @NonNls public static final String ASYNC_DELETE_EXTENSION = ".__del__"; - public static final TObjectHashingStrategy PATH_HASHING_STRATEGY; - static { - if (SystemInfo.isFileSystemCaseSensitive) { - @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"}) - final TObjectHashingStrategy canonical = TObjectHashingStrategy.CANONICAL; - PATH_HASHING_STRATEGY = canonical; - } - else { - PATH_HASHING_STRATEGY = CaseInsensitiveStringHashingStrategy.INSTANCE; - } - } + @SuppressWarnings({"unchecked"}) + public static final TObjectHashingStrategy PATH_HASHING_STRATEGY = + SystemInfo.isFileSystemCaseSensitive ? TObjectHashingStrategy.CANONICAL : CaseInsensitiveStringHashingStrategy.INSTANCE; private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.io.FileUtil"); @@ -71,58 +64,20 @@ public class FileUtil extends FileUtilRt { @Nullable public static String getRelativePath(File base, File file) { - if (base == null || file == null) return null; - - if (!base.isDirectory()) { - base = base.getParentFile(); - if (base == null) return null; - } - - if (base.equals(file)) return "."; - - final String filePath = file.getAbsolutePath(); - String basePath = base.getAbsolutePath(); - return getRelativePath(basePath, filePath, File.separatorChar); + return FileUtilRt.getRelativePath(base, file); } + @Nullable public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator) { - return getRelativePath(basePath, filePath, separator, SystemInfo.isFileSystemCaseSensitive); - } - - private static String ensureEnds(@NotNull String s, final char endsWith) { - return StringUtil.endsWithChar(s, endsWith) ? s : s + endsWith; + return FileUtilRt.getRelativePath(basePath, filePath, separator); } + @Nullable public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator, final boolean caseSensitive) { - basePath = ensureEnds(basePath, separator); - - String basePathToCompare = caseSensitive ? basePath : basePath.toLowerCase(); - String filePathToCompare = caseSensitive ? filePath : filePath.toLowerCase(); - if (basePathToCompare.equals(ensureEnds(filePathToCompare, separator))) return "."; - int len = 0; - int lastSeparatorIndex = 0; // need this for cases like this: base="/temp/abcde/base" and file="/temp/ab" - while (len < filePath.length() && len < basePath.length() && filePathToCompare.charAt(len) == basePathToCompare.charAt(len)) { - if (basePath.charAt(len) == separator) { - lastSeparatorIndex = len; - } - len++; - } - - if (len == 0) return null; - - StringBuilder relativePath = new StringBuilder(); - for (int i = len; i < basePath.length(); i++) { - if (basePath.charAt(i) == separator) { - relativePath.append(".."); - relativePath.append(separator); - } - } - relativePath.append(filePath.substring(lastSeparatorIndex + 1)); - - return relativePath.toString(); + return FileUtilRt.getRelativePath(basePath, filePath, separator, caseSensitive); } public static boolean isAbsolute(@NotNull String path) { @@ -604,11 +559,7 @@ public class FileUtil extends FileUtilRt { @NotNull public static String getNameWithoutExtension(@NotNull String name) { - int i = name.lastIndexOf('.'); - if (i != -1) { - name = name.substring(0, i); - } - return name; + return FileUtilRt.getNameWithoutExtension(name); } public static String createSequentFileName(@NotNull File aParentFolder, @NotNull @NonNls String aFilePrefix, @NotNull String aExtension) { @@ -631,12 +582,12 @@ public class FileUtil extends FileUtilRt { @NotNull public static String toSystemDependentName(@NonNls @NotNull String aFileName) { - return aFileName.replace('/', File.separatorChar).replace('\\', File.separatorChar); + return FileUtilRt.toSystemDependentName(aFileName); } @NotNull public static String toSystemIndependentName(@NonNls @NotNull String aFileName) { - return aFileName.replace('\\', '/'); + return FileUtilRt.toSystemIndependentName(aFileName); } @NotNull @@ -745,9 +696,7 @@ public class FileUtil extends FileUtilRt { @NotNull public static String getExtension(@NotNull String fileName) { - int index = fileName.lastIndexOf('.'); - if (index < 0) return ""; - return fileName.substring(index + 1).toLowerCase(); + return FileUtilRt.getExtension(fileName); } @NotNull @@ -1128,19 +1077,121 @@ public class FileUtil extends FileUtilRt { return firstLine.contains(marker); } + @NotNull + public static File createTempDirectory(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { + return FileUtilRt.createTempDirectory(prefix, suffix); + } + + @NotNull + public static File createTempDirectory(File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { + return FileUtilRt.createTempDirectory(dir, prefix, suffix); + } + + @NotNull + public static File createTempFile(@NonNls File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean create) throws IOException { + return FileUtilRt.createTempFile(dir, prefix, suffix, create); + } + + @NotNull + public static File createTempFile(@NonNls File dir, + @NotNull @NonNls String prefix, + @Nullable @NonNls String suffix, + boolean create, + boolean deleteOnExit) throws IOException { + return FileUtilRt.createTempFile(dir, prefix, suffix, create, deleteOnExit); + } + + @NotNull + public static File createTempFile(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { + return FileUtilRt.createTempFile(prefix, suffix); + } + + @NotNull + public static File createTempFile(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean deleteOnExit) throws IOException { + return FileUtilRt.createTempFile(prefix, suffix, deleteOnExit); + } + + @NotNull + public static String getTempDirectory() { + return FileUtilRt.getTempDirectory(); + } + + @TestOnly + public static void resetCanonicalTempPathCache(final String tempPath) { + FileUtilRt.resetCanonicalTempPathCache(tempPath); + } + + @NotNull + public static File generateRandomTemporaryPath() throws IOException { + return FileUtilRt.generateRandomTemporaryPath(); + } + + public static void setExecutableAttribute(@NotNull String path, boolean executableFlag) throws IOException { + FileUtilRt.setExecutableAttribute(path, executableFlag); + } + + @NotNull + public static String loadFile(@NotNull File file) throws IOException { + return FileUtilRt.loadFile(file); + } + + @NotNull + public static String loadFile(@NotNull File file, boolean convertLineSeparators) throws IOException { + return FileUtilRt.loadFile(file, convertLineSeparators); + } + + @NotNull + public static String loadFile(@NotNull File file, @Nullable @NonNls String encoding) throws IOException { + return FileUtilRt.loadFile(file, encoding); + } + + @NotNull + public static String loadFile(@NotNull File file, @Nullable @NonNls String encoding, boolean convertLineSeparators) throws IOException { + return FileUtilRt.loadFile(file, encoding, convertLineSeparators); + } + + @NotNull + public static char[] loadFileText(@NotNull File file) throws IOException { + return FileUtilRt.loadFileText(file); + } + + @NotNull + public static char[] loadFileText(@NotNull File file, @Nullable @NonNls String encoding) throws IOException { + return FileUtilRt.loadFileText(file, encoding); + } + + @NotNull + public static char[] loadText(@NotNull Reader reader, int length) throws IOException { + return FileUtilRt.loadText(reader, length); + } + + @NotNull + public static byte[] loadBytes(@NotNull InputStream stream) throws IOException { + return FileUtilRt.loadBytes(stream); + } + + @NotNull + public static byte[] loadBytes(@NotNull InputStream stream, int length) throws IOException { + return FileUtilRt.loadBytes(stream, length); + } + // copied from FileSystem: they are package local there public static final int BA_EXISTS = 0x01; public static final int BA_REGULAR = 0x02; public static final int BA_DIRECTORY = 0x04; public static final int BA_HIDDEN = 0x08; + @MagicConstant(flags = {BA_EXISTS, BA_REGULAR, BA_DIRECTORY, BA_HIDDEN}) + public @interface FileBooleanAttributes {} + // todo[r.sh] use NIO2 API after migration to JDK 7 // returns -1 if could not get attributes - @MagicConstant(flags = {BA_EXISTS, BA_REGULAR, BA_DIRECTORY, BA_HIDDEN}) + @FileBooleanAttributes public static int getBooleanAttributes(@NotNull File f) { if (JAVA_IO_FILESYSTEM_GET_BOOLEAN_ATTRIBUTES_METHOD != null) { try { Object flags = JAVA_IO_FILESYSTEM_GET_BOOLEAN_ATTRIBUTES_METHOD.invoke(JAVA_IO_FILESYSTEM, f); + //noinspection MagicConstant return ((Integer)flags).intValue(); } catch (Exception ignored) { } @@ -1148,10 +1199,6 @@ public class FileUtil extends FileUtilRt { return -1; } - @MagicConstant(flags = {BA_EXISTS, BA_REGULAR, BA_DIRECTORY, BA_HIDDEN}) - public @interface FileBooleanAttributes {} - - static { Object fs; Method getBooleanAttributes; diff --git a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java index c687682275dd..cc4a6340f6ac 100644 --- a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java +++ b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java @@ -36,7 +36,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; //TeamCity inherits StringUtil: do not add private constructors!!! -@SuppressWarnings({"UtilityClassWithoutPrivateConstructor"}) +@SuppressWarnings({"UtilityClassWithoutPrivateConstructor", "MethodOverridesStaticMethodOfSuperclass"}) public class StringUtil extends StringUtilRt { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.text.StringUtil"); @@ -803,7 +803,7 @@ public class StringUtil extends StringUtilRt { } public static boolean endsWithChar(@Nullable CharSequence s, char suffix) { - return s != null && s.length() != 0 && s.charAt(s.length() - 1) == suffix; + return StringUtilRt.endsWithChar(s, suffix); } @NotNull @@ -2010,11 +2010,13 @@ public class StringUtil extends StringUtilRt { while (j < string2Length && isDigit(string2.charAt(j))) j++; String digits1 = string1.substring(startNum1, i); String digits2 = string2.substring(startNum2, j); - if (digits1.length() != digits2.length()) - return digits1.length() - digits2.length(); + if (digits1.length() != digits2.length()) { + return digits1.length() - digits2.length(); + } int numberDiff = digits1.compareTo(digits2); - if (numberDiff != 0) + if (numberDiff != 0) { return numberDiff; + } i--; j--; final int lengthDiff = (i - startNum1) - (j - startNum2); @@ -2156,4 +2158,67 @@ public class StringUtil extends StringUtilRt { } return buffer.toString(); } + + public static boolean charsEqualIgnoreCase(char a, char b) { + return StringUtilRt.charsEqualIgnoreCase(a, b); + } + + public static char toUpperCase(char a) { + return StringUtilRt.toUpperCase(a); + } + + public static char toLowerCase(final char a) { + return StringUtilRt.toLowerCase(a); + } + + @NotNull + public static String convertLineSeparators(@NotNull String text) { + return StringUtilRt.convertLineSeparators(text); + } + + @NotNull + public static String convertLineSeparators(@NotNull String text, boolean keepCarriageReturn) { + return StringUtilRt.convertLineSeparators(text, keepCarriageReturn); + } + + @NotNull + public static String convertLineSeparators(@NotNull String text, @NotNull String newSeparator) { + return StringUtilRt.convertLineSeparators(text, newSeparator); + } + + @NotNull + public static String convertLineSeparators(@NotNull String text, @NotNull String newSeparator, @Nullable int[] offsetsToKeep) { + return StringUtilRt.convertLineSeparators(text, newSeparator, offsetsToKeep); + } + + @NotNull + public static String convertLineSeparators(@NotNull String text, + @NotNull String newSeparator, + @Nullable int[] offsetsToKeep, + boolean keepCarriageReturn) { + return StringUtilRt.convertLineSeparators(text, newSeparator, offsetsToKeep, keepCarriageReturn); + } + + public static int parseInt(final String string, final int defaultValue) { + return StringUtilRt.parseInt(string, defaultValue); + } + + public static double parseDouble(final String string, final double defaultValue) { + return StringUtilRt.parseDouble(string, defaultValue); + } + + @NotNull + public static String getShortName(@NotNull Class aClass) { + return StringUtilRt.getShortName(aClass); + } + + @NotNull + public static String getShortName(@NotNull String fqName) { + return StringUtilRt.getShortName(fqName); + } + + @NotNull + public static String getShortName(@NotNull String fqName, char separator) { + return StringUtilRt.getShortName(fqName, separator); + } } diff --git a/platform/util/src/com/intellij/psi/codeStyle/NameUtil.java b/platform/util/src/com/intellij/psi/codeStyle/NameUtil.java index 4621227edbfc..8c61b6c90e1d 100644 --- a/platform/util/src/com/intellij/psi/codeStyle/NameUtil.java +++ b/platform/util/src/com/intellij/psi/codeStyle/NameUtil.java @@ -264,53 +264,71 @@ public class NameUtil { continue; } - StringBuilder buffer = new StringBuilder(); - buffer.append(prefix); - - if (upperCaseStyle) { - startWord = startWord.toUpperCase(); - } - else { - if (prefix.length() == 0 || StringUtil.endsWithChar(prefix, '_')) { - startWord = startWord.toLowerCase(); - } - else { - startWord = Character.toUpperCase(c) + startWord.substring(1); - } - } - buffer.append(startWord); - - for (int i = words.length - wordCount + 1; i < words.length; i++) { - String word = words[i]; - String prevWord = words[i - 1]; - if (upperCaseStyle) { - word = word.toUpperCase(); - if (prevWord.charAt(prevWord.length() - 1) != '_' && word.charAt(0) != '_') { - word = "_" + word; - } - } - else { - if (prevWord.charAt(prevWord.length() - 1) == '_') { - word = word.toLowerCase(); - } - } - buffer.append(word); - } - - String suggestion = buffer.toString(); - - if (isArray) { - suggestion = StringUtil.pluralize(suggestion); - if (upperCaseStyle) { - suggestion = suggestion.toUpperCase(); - } - } - - answer.add(suggestion + suffix); + answer.add(compoundSuggestion(prefix, upperCaseStyle, words, wordCount, startWord, c, isArray, true) + suffix); + answer.add(compoundSuggestion(prefix, upperCaseStyle, words, wordCount, startWord, c, isArray, false) + suffix); } return answer; } + private static String compoundSuggestion(String prefix, + boolean upperCaseStyle, + String[] words, + int wordCount, + String startWord, + char c, + boolean isArray, + boolean skip_) { + StringBuilder buffer = new StringBuilder(); + + buffer.append(prefix); + + if (upperCaseStyle) { + startWord = startWord.toUpperCase(); + } + else { + if (prefix.length() == 0 || StringUtil.endsWithChar(prefix, '_')) { + startWord = startWord.toLowerCase(); + } + else { + startWord = Character.toUpperCase(c) + startWord.substring(1); + } + } + buffer.append(startWord); + + for (int i = words.length - wordCount + 1; i < words.length; i++) { + String word = words[i]; + String prevWord = words[i - 1]; + if (upperCaseStyle) { + word = word.toUpperCase(); + if (prevWord.charAt(prevWord.length() - 1) != '_' && word.charAt(0) != '_') { + word = "_" + word; + } + } + else { + if (prevWord.charAt(prevWord.length() - 1) == '_') { + word = word.toLowerCase(); + } + + if (skip_) { + if (word.equals("_")) continue; + if (prevWord.equals("_")) { + word = StringUtil.capitalize(word); + } + } + } + buffer.append(word); + } + + String suggestion = buffer.toString(); + if (isArray) { + suggestion = StringUtil.pluralize(suggestion); + if (upperCaseStyle) { + suggestion = suggestion.toUpperCase(); + } + } + return suggestion; + } + private static boolean isWordStart(char p) { return Character.isUpperCase(p) || Character.isDigit(p); } diff --git a/platform/util/src/com/intellij/util/ArrayUtil.java b/platform/util/src/com/intellij/util/ArrayUtil.java index a4f92f60f5a8..d54b0d612219 100644 --- a/platform/util/src/com/intellij/util/ArrayUtil.java +++ b/platform/util/src/com/intellij/util/ArrayUtil.java @@ -30,6 +30,7 @@ import java.util.List; /** * Author: msk */ +@SuppressWarnings("MethodOverridesStaticMethodOfSuperclass") public class ArrayUtil extends ArrayUtilRt { public static final short[] EMPTY_SHORT_ARRAY = ArrayUtilRt.EMPTY_SHORT_ARRAY; public static final char[] EMPTY_CHAR_ARRAY = ArrayUtilRt.EMPTY_CHAR_ARRAY; @@ -680,4 +681,9 @@ public class ArrayUtil extends ArrayUtilRt { public static T[] join(T[] array1, T[] array2) { return mergeArrays(array1, array2); } + + @NotNull + public static String[] toStringArray(@NotNull Collection collection) { + return ArrayUtilRt.toStringArray(collection); + } } diff --git a/platform/util/src/com/intellij/util/containers/ContainerUtil.java b/platform/util/src/com/intellij/util/containers/ContainerUtil.java index 5f3b4e7f39c0..94d8cc11b088 100644 --- a/platform/util/src/com/intellij/util/containers/ContainerUtil.java +++ b/platform/util/src/com/intellij/util/containers/ContainerUtil.java @@ -29,8 +29,9 @@ import org.jetbrains.annotations.Nullable; import java.lang.reflect.Array; import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; -@SuppressWarnings({"UtilityClassWithoutPrivateConstructor", "unchecked"}) +@SuppressWarnings({"UtilityClassWithoutPrivateConstructor", "unchecked", "MethodOverridesStaticMethodOfSuperclass"}) public class ContainerUtil extends ContainerUtilRt { private static final int INSERTION_SORT_THRESHOLD = 10; @@ -1272,6 +1273,7 @@ public class ContainerUtil extends ContainerUtilRt { return true; } + @Nullable public static List trimToSize(List list) { if (list == null) return null; if (list.isEmpty()) return Collections.emptyList(); @@ -1282,4 +1284,52 @@ public class ContainerUtil extends ContainerUtilRt { return list; } + + @NotNull + public static List emptyList() { + return ContainerUtilRt.emptyList(); + } + + @NotNull + public static CopyOnWriteArrayList createEmptyCOWList() { + return ContainerUtilRt.createEmptyCOWList(); + } + + public static void addIfNotNull(final T element, @NotNull Collection result) { + ContainerUtilRt.addIfNotNull(element, result); + } + + public static void addIfNotNull(@NotNull Collection result, @Nullable final T element) { + ContainerUtilRt.addIfNotNull(result, element); + } + + @NotNull + public static List map2List(@NotNull T[] array, @NotNull Function mapper) { + return ContainerUtilRt.map2List(array, mapper); + } + + @NotNull + public static List map2List(@NotNull Collection collection, @NotNull Function mapper) { + return ContainerUtilRt.map2List(collection, mapper); + } + + @NotNull + public static Set map2Set(@NotNull T[] collection, @NotNull Function mapper) { + return ContainerUtilRt.map2Set(collection, mapper); + } + + @NotNull + public static Set map2Set(@NotNull Collection collection, @NotNull Function mapper) { + return ContainerUtilRt.map2Set(collection, mapper); + } + + @NotNull + public static T[] toArray(@NotNull List collection, @NotNull T[] array) { + return ContainerUtilRt.toArray(collection, array); + } + + @NotNull + public static T[] toArray(@NotNull Collection c, @NotNull T[] sample) { + return ContainerUtilRt.toArray(c, sample); + } } diff --git a/platform/util/util.iml b/platform/util/util.iml index 378b380da974..27332eb5ba61 100644 --- a/platform/util/util.iml +++ b/platform/util/util.iml @@ -10,7 +10,6 @@ - @@ -19,6 +18,7 @@ + diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/RollbackAction.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/RollbackAction.java index 8754e23517fe..fa2bb9a7d077 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/RollbackAction.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/RollbackAction.java @@ -32,6 +32,7 @@ import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ChangeListManager; @@ -44,6 +45,7 @@ import com.intellij.openapi.vcs.rollback.RollbackEnvironment; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.containers.CollectionFactory; +import com.intellij.util.ui.UIUtil; import com.intellij.vcsUtil.RollbackUtil; import org.jetbrains.annotations.Nullable; @@ -51,7 +53,7 @@ import java.util.*; import static com.intellij.openapi.ui.Messages.getQuestionIcon; import static com.intellij.openapi.ui.Messages.showYesNoDialog; -import static java.util.Arrays.*; +import static java.util.Arrays.asList; public class RollbackAction extends AnAction implements DumbAware { public void update(AnActionEvent e) { @@ -197,12 +199,12 @@ public class RollbackAction extends AnAction implements DumbAware { } private static void rollbackModifiedWithoutEditing(final Project project, final LinkedHashSet modifiedWithoutEditing) { - final String operationName = RollbackUtil.getRollbackOperationName(project); + final String operationName = StringUtil.decapitalize(UIUtil.removeMnemonic(RollbackUtil.getRollbackOperationName(project))); String message = (modifiedWithoutEditing.size() == 1) ? VcsBundle.message("rollback.modified.without.editing.confirm.single", - modifiedWithoutEditing.iterator().next().getPresentableUrl(), operationName) + operationName, modifiedWithoutEditing.iterator().next().getPresentableUrl()) : VcsBundle.message("rollback.modified.without.editing.confirm.multiple", - modifiedWithoutEditing.size(), operationName); + operationName, modifiedWithoutEditing.size()); int rc = showYesNoDialog(project, message, VcsBundle.message("changes.action.rollback.title", operationName), getQuestionIcon()); if (rc != 0) { return; @@ -237,7 +239,7 @@ public class RollbackAction extends AnAction implements DumbAware { } if (!exceptions.isEmpty()) { AbstractVcsHelper.getInstance(project).showErrors(exceptions, VcsBundle.message("rollback.modified.without.checkout.error.tab", - operationName)); + operationName)); } VirtualFileManager.getInstance().refresh(true, new Runnable() { public void run() { diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/update/FileOrDirectoryTreeNode.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/update/FileOrDirectoryTreeNode.java index 8b5bfe9b2209..ca66b7a3048e 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/update/FileOrDirectoryTreeNode.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/update/FileOrDirectoryTreeNode.java @@ -17,6 +17,7 @@ package com.intellij.openapi.vcs.update; import com.intellij.openapi.Disposable; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.LocalFileSystem; @@ -46,8 +47,7 @@ public abstract class FileOrDirectoryTreeNode extends AbstractTreeNode implement protected FileOrDirectoryTreeNode(@NotNull String path, SimpleTextAttributes invalidAttributes, Project project, String parentPath) { String preparedPath = path.replace(File.separatorChar, '/'); - String url = VirtualFileManager.constructUrl(LocalFileSystem.getInstance().getProtocol(), - preparedPath); + String url = VirtualFileManager.constructUrl(LocalFileSystem.getInstance().getProtocol(), preparedPath); setUserObject(VirtualFilePointerManager.getInstance().create(url, this, this)); myFile = new File(getFilePath()); myInvalidAttributes = invalidAttributes; @@ -55,6 +55,7 @@ public abstract class FileOrDirectoryTreeNode extends AbstractTreeNode implement myName = parentPath == null ? myFile.getAbsolutePath() : myFile.getName(); } + @Override public String getName() { return myName; } @@ -63,10 +64,12 @@ public abstract class FileOrDirectoryTreeNode extends AbstractTreeNode implement return getFilePointer().getPresentableUrl(); } - public void beforeValidityChanged(VirtualFilePointer[] pointers) { + @Override + public void beforeValidityChanged(@NotNull VirtualFilePointer[] pointers) { } - public void validityChanged(VirtualFilePointer[] pointers) { + @Override + public void validityChanged(@NotNull VirtualFilePointer[] pointers) { if (!getFilePointer().isValid()) { AbstractTreeNode parent = (AbstractTreeNode) getParent(); if (parent != null && parent.getSupportsDeletion()) { @@ -79,6 +82,7 @@ public abstract class FileOrDirectoryTreeNode extends AbstractTreeNode implement } } + @Override public void setUserObject(final Object userObject) { final Object oldObject = getUserObject(); try { @@ -86,8 +90,8 @@ public abstract class FileOrDirectoryTreeNode extends AbstractTreeNode implement } finally { if (oldObject instanceof VirtualFilePointer) { - final VirtualFilePointer pointer = (VirtualFilePointer)oldObject; - VirtualFilePointerManager.getInstance().kill(pointer, this); + VirtualFilePointer pointer = (VirtualFilePointer)oldObject; + Disposer.dispose((Disposable)pointer); } } } @@ -96,6 +100,7 @@ public abstract class FileOrDirectoryTreeNode extends AbstractTreeNode implement return (VirtualFilePointer)getUserObject(); } + @Override public SimpleTextAttributes getAttributes() { if (!getFilePointer().isValid()) { return myInvalidAttributes; @@ -116,11 +121,13 @@ public abstract class FileOrDirectoryTreeNode extends AbstractTreeNode implement return myFileStatusToAttributeMap.get(status); } + @Override public boolean getSupportsDeletion() { AbstractTreeNode parent = (AbstractTreeNode)getParent(); return parent != null && parent.getSupportsDeletion(); } + @Override public void dispose() { } } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsConfigurationDialogFactory.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsConfigurationDialogFactory.java index c8f51b89729d..934d92cc5fd0 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsConfigurationDialogFactory.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/BreakpointsConfigurationDialogFactory.java @@ -117,10 +117,7 @@ public class BreakpointsConfigurationDialogFactory { JComponent contentComponent = null; if (myPanels.size() > 1) { - final Disposable tabbedPaneDisposable = new Disposable() { - public void dispose() { - } - }; + final Disposable tabbedPaneDisposable = Disposer.newDisposable(); final TabbedPaneWrapper tabbedPane = new TabbedPaneWrapper(tabbedPaneDisposable); for (AbstractBreakpointPanel breakpointPanel : myPanels) { addPanel(breakpointPanel, tabbedPane); diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/BaseInspectionVisitor.java b/plugins/InspectionGadgets/src/com/siyeh/ig/BaseInspectionVisitor.java index aedb7b302c1d..41743b042617 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/BaseInspectionVisitor.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/BaseInspectionVisitor.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2011 Dave Griffith, Bas Leijdekkers + * Copyright 2003-2012 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/migration/StringBufferReplaceableByStringBuilderInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/migration/StringBufferReplaceableByStringBuilderInspection.java index 24766bf59225..f169230f8ae9 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/migration/StringBufferReplaceableByStringBuilderInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/migration/StringBufferReplaceableByStringBuilderInspection.java @@ -29,6 +29,7 @@ import com.siyeh.ig.psiutils.TypeUtils; import com.siyeh.ig.psiutils.VariableAccessUtils; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.*; @@ -62,6 +63,27 @@ public class StringBufferReplaceableByStringBuilderInspection extends BaseInspec return new StringBufferMayBeStringBuilderFix(); } + @Nullable + private static PsiNewExpression getNewStringBuffer(PsiExpression expression) { + if (expression == null) { + return null; + } + else if (expression instanceof PsiNewExpression) { + return (PsiNewExpression)expression; + } + else if (expression instanceof PsiMethodCallExpression) { + final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression; + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); + @NonNls final String methodName = methodExpression.getReferenceName(); + if (!"append".equals(methodName)) { + return null; + } + final PsiExpression qualifier = methodExpression.getQualifierExpression(); + return getNewStringBuffer(qualifier); + } + return null; + } + private static class StringBufferMayBeStringBuilderFix extends InspectionGadgetsFix { @@ -99,8 +121,8 @@ public class StringBufferReplaceableByStringBuilderInspection extends BaseInspec private static void replaceWithStringBuilder(PsiJavaCodeReferenceElement newClassReference, PsiTypeElement newTypeElement, PsiVariable variable) { - final PsiExpression initializer = variable.getInitializer(); - if (!(initializer instanceof PsiNewExpression)) { + final PsiExpression initializer = getNewStringBuffer(variable.getInitializer()); + if (initializer == null) { return; } final PsiNewExpression newExpression = (PsiNewExpression)initializer; @@ -162,7 +184,7 @@ public class StringBufferReplaceableByStringBuilderInspection extends BaseInspec if (initializer == null) { return false; } - if (!isNewStringBuffer(initializer)) { + if (getNewStringBuffer(initializer) == null) { return false; } if (VariableAccessUtils.variableIsAssigned(variable, context)) { @@ -182,25 +204,5 @@ public class StringBufferReplaceableByStringBuilderInspection extends BaseInspec } return true; } - - private static boolean isNewStringBuffer(PsiExpression expression) { - if (expression == null) { - return false; - } - else if (expression instanceof PsiNewExpression) { - return true; - } - else if (expression instanceof PsiMethodCallExpression) { - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression; - final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); - @NonNls final String methodName = methodExpression.getReferenceName(); - if (!"append".equals(methodName)) { - return false; - } - final PsiExpression qualifier = methodExpression.getQualifierExpression(); - return isNewStringBuffer(qualifier); - } - return false; - } } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/migration/UnnecessaryBoxingInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/migration/UnnecessaryBoxingInspection.java index d7fade7e0a3d..3a5b31e2b69e 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/migration/UnnecessaryBoxingInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/migration/UnnecessaryBoxingInspection.java @@ -26,6 +26,7 @@ import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.psiutils.MethodCallUtils; +import com.siyeh.ig.psiutils.ParenthesesUtils; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -35,8 +36,7 @@ import java.util.Map; public class UnnecessaryBoxingInspection extends BaseInspection { - @NonNls static final Map boxedPrimitiveMap = - new HashMap(8); + @NonNls static final Map boxedPrimitiveMap = new HashMap(8); static { boxedPrimitiveMap.put(CommonClassNames.JAVA_LANG_INTEGER, "int"); @@ -52,8 +52,7 @@ public class UnnecessaryBoxingInspection extends BaseInspection { @Override @NotNull public String getDisplayName() { - return InspectionGadgetsBundle.message( - "unnecessary.boxing.display.name"); + return InspectionGadgetsBundle.message("unnecessary.boxing.display.name"); } @Override @@ -64,8 +63,7 @@ public class UnnecessaryBoxingInspection extends BaseInspection { @Override @NotNull protected String buildErrorString(Object... infos) { - return InspectionGadgetsBundle.message( - "unnecessary.boxing.problem.descriptor"); + return InspectionGadgetsBundle.message("unnecessary.boxing.problem.descriptor"); } @Override @@ -81,8 +79,7 @@ public class UnnecessaryBoxingInspection extends BaseInspection { } @Override - public void doFix(@NotNull Project project, ProblemDescriptor descriptor) - throws IncorrectOperationException { + public void doFix(@NotNull Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiCallExpression expression = (PsiCallExpression)descriptor.getPsiElement(); final PsiType boxedType = expression.getType(); if (boxedType == null) { @@ -96,16 +93,22 @@ public class UnnecessaryBoxingInspection extends BaseInspection { if (arguments.length != 1) { return; } - final PsiType argumentType = arguments[0].getType(); - if (argumentType == null) { + final PsiExpression unboxedExpression = arguments[0]; + final PsiType unboxedType = unboxedExpression.getType(); + if (unboxedType == null) { return; } - final String cast = getCastString(argumentType, boxedType); + final String cast = getCastString(unboxedType, boxedType); if (cast == null) { return; } - final String newExpression = arguments[0].getText(); - replaceExpression(expression, cast + newExpression); + final int precedence = ParenthesesUtils.getPrecedence(unboxedExpression); + if (cast.length() > 0 && precedence > ParenthesesUtils.TYPE_CAST_PRECEDENCE) { + replaceExpression(expression, cast + '(' + unboxedExpression.getText() + ')'); + } + else { + replaceExpression(expression, cast + unboxedExpression.getText()); + } } @Nullable @@ -130,12 +133,10 @@ public class UnnecessaryBoxingInspection extends BaseInspection { return new UnnecessaryBoxingVisitor(); } - private static class UnnecessaryBoxingVisitor - extends BaseInspectionVisitor { + private static class UnnecessaryBoxingVisitor extends BaseInspectionVisitor { @Override - public void visitNewExpression( - @NotNull PsiNewExpression expression) { + public void visitNewExpression(@NotNull PsiNewExpression expression) { if (!PsiUtil.isLanguageLevel5OrHigher(expression)) { return; } @@ -144,8 +145,7 @@ public class UnnecessaryBoxingInspection extends BaseInspection { if (constructorType == null) { return; } - final String constructorTypeText = - constructorType.getCanonicalText(); + final String constructorTypeText = constructorType.getCanonicalText(); if (!boxedPrimitiveMap.containsKey(constructorTypeText)) { return; } @@ -153,8 +153,7 @@ public class UnnecessaryBoxingInspection extends BaseInspection { if (constructor == null) { return; } - final PsiParameterList parameterList = - constructor.getParameterList(); + final PsiParameterList parameterList = constructor.getParameterList(); if (parameterList.getParametersCount() != 1) { return; } @@ -162,8 +161,7 @@ public class UnnecessaryBoxingInspection extends BaseInspection { final PsiParameter parameter = parameters[0]; final PsiType parameterType = parameter.getType(); final String parameterTypeText = parameterType.getCanonicalText(); - final String boxableConstructorType = - boxedPrimitiveMap.get(constructorTypeText); + final String boxableConstructorType = boxedPrimitiveMap.get(constructorTypeText); if (!boxableConstructorType.equals(parameterTypeText)) { return; } @@ -174,8 +172,7 @@ public class UnnecessaryBoxingInspection extends BaseInspection { } @Override - public void visitMethodCallExpression( - PsiMethodCallExpression expression) { + public void visitMethodCallExpression(PsiMethodCallExpression expression) { if (!PsiUtil.isLanguageLevel5OrHigher(expression)) { return; } @@ -188,20 +185,17 @@ public class UnnecessaryBoxingInspection extends BaseInspection { if (!(arguments[0].getType() instanceof PsiPrimitiveType)) { return; } - final PsiReferenceExpression methodExpression = - expression.getMethodExpression(); + final PsiReferenceExpression methodExpression = expression.getMethodExpression(); @NonNls final String referenceName = methodExpression.getReferenceName(); if (!"valueOf".equals(referenceName)) { return; } - final PsiExpression qualifierExpression = - methodExpression.getQualifierExpression(); + final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); if (!(qualifierExpression instanceof PsiReferenceExpression)) { return; } - final PsiReferenceExpression referenceExpression = - (PsiReferenceExpression)qualifierExpression; + final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)qualifierExpression; final String canonicalText = referenceExpression.getCanonicalText(); if (!boxedPrimitiveMap.containsKey(canonicalText)) { return; @@ -217,13 +211,11 @@ public class UnnecessaryBoxingInspection extends BaseInspection { while (parent instanceof PsiParenthesizedExpression) { parent = parent.getParent(); } - if (parent instanceof PsiExpressionStatement || - parent instanceof PsiReferenceExpression) { + if (parent instanceof PsiExpressionStatement || parent instanceof PsiReferenceExpression) { return false; } else if (parent instanceof PsiTypeCastExpression) { - final PsiTypeCastExpression castExpression = - (PsiTypeCastExpression)parent; + final PsiTypeCastExpression castExpression = (PsiTypeCastExpression)parent; final PsiType castType = castExpression.getType(); if (castType instanceof PsiClassType) { final PsiClassType classType = (PsiClassType)castType; @@ -234,12 +226,9 @@ public class UnnecessaryBoxingInspection extends BaseInspection { } } else if (parent instanceof PsiConditionalExpression) { - final PsiConditionalExpression conditionalExpression = - (PsiConditionalExpression)parent; - final PsiExpression thenExpression = - conditionalExpression.getThenExpression(); - final PsiExpression elseExpression = - conditionalExpression.getElseExpression(); + final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)parent; + final PsiExpression thenExpression = conditionalExpression.getThenExpression(); + final PsiExpression elseExpression = conditionalExpression.getElseExpression(); if (elseExpression == null || thenExpression == null) { return false; } @@ -247,8 +236,7 @@ public class UnnecessaryBoxingInspection extends BaseInspection { final PsiType type = elseExpression.getType(); return type instanceof PsiPrimitiveType; } - else if (PsiTreeUtil.isAncestor(elseExpression, expression, - false)) { + else if (PsiTreeUtil.isAncestor(elseExpression, expression, false)) { final PsiType type = thenExpression.getType(); return type instanceof PsiPrimitiveType; } @@ -257,8 +245,7 @@ public class UnnecessaryBoxingInspection extends BaseInspection { } } else if (parent instanceof PsiBinaryExpression) { - final PsiBinaryExpression binaryExpression = - (PsiBinaryExpression)parent; + final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)parent; final PsiExpression lhs = binaryExpression.getLOperand(); final PsiExpression rhs = binaryExpression.getROperand(); if (rhs == null) { @@ -273,31 +260,22 @@ public class UnnecessaryBoxingInspection extends BaseInspection { return false; } if (PsiTreeUtil.isAncestor(rhs, expression, false)) { - final PsiPrimitiveType unboxedType = - PsiPrimitiveType.getUnboxedType(rhsType); - return unboxedType != null && - unboxedType.isAssignableFrom(lhsType); + final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(rhsType); + return unboxedType != null && unboxedType.isAssignableFrom(lhsType); } else { - final PsiPrimitiveType unboxedType = - PsiPrimitiveType.getUnboxedType(lhsType); - return unboxedType != null && - unboxedType.isAssignableFrom(rhsType); + final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(lhsType); + return unboxedType != null && unboxedType.isAssignableFrom(rhsType); } } - final PsiMethodCallExpression containingMethodCallExpression = - getParentMethodCallExpression(expression); - return containingMethodCallExpression == null || - isSameMethodCalledWithoutBoxing( - containingMethodCallExpression, expression); + final PsiMethodCallExpression containingMethodCallExpression = getParentMethodCallExpression(expression); + return containingMethodCallExpression == null || isSameMethodCalledWithoutBoxing(containingMethodCallExpression, expression); } @Nullable - private static PsiMethodCallExpression getParentMethodCallExpression( - @NotNull PsiElement expression) { + private static PsiMethodCallExpression getParentMethodCallExpression(@NotNull PsiElement expression) { final PsiElement parent = expression.getParent(); - if (parent instanceof PsiParenthesizedExpression || - parent instanceof PsiExpressionList) { + if (parent instanceof PsiParenthesizedExpression || parent instanceof PsiExpressionList) { return getParentMethodCallExpression(parent); } else if (parent instanceof PsiMethodCallExpression) { @@ -308,22 +286,18 @@ public class UnnecessaryBoxingInspection extends BaseInspection { } } - private static boolean isSameMethodCalledWithoutBoxing( - @NotNull PsiMethodCallExpression methodCallExpression, + private static boolean isSameMethodCalledWithoutBoxing(@NotNull PsiMethodCallExpression methodCallExpression, @NotNull PsiExpression boxingExpression) { - final PsiExpressionList argumentList = - methodCallExpression.getArgumentList(); + final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); final PsiExpression[] expressions = argumentList.getExpressions(); - final PsiReferenceExpression methodExpression = - methodCallExpression.getMethodExpression(); + final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); final PsiElement element = methodExpression.resolve(); if (!(element instanceof PsiMethod)) { return false; } final PsiMethod originalMethod = (PsiMethod)element; final String name = originalMethod.getName(); - final PsiClass containingClass = - originalMethod.getContainingClass(); + final PsiClass containingClass = originalMethod.getContainingClass(); if (containingClass == null) { return false; } @@ -332,8 +306,7 @@ public class UnnecessaryBoxingInspection extends BaseInspection { final PsiExpression expression = expressions[i]; final PsiType type = expression.getType(); if (boxingExpression.equals(expression)) { - final PsiPrimitiveType unboxedType = - PsiPrimitiveType.getUnboxedType(type); + final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(type); if (unboxedType == null) { return false; } @@ -343,12 +316,10 @@ public class UnnecessaryBoxingInspection extends BaseInspection { types[i] = type; } } - final PsiMethod[] methods = - containingClass.findMethodsByName(name, true); + final PsiMethod[] methods = containingClass.findMethodsByName(name, true); for (PsiMethod method : methods) { if (!originalMethod.equals(method)) { - if (MethodCallUtils.isApplicable(method, - PsiSubstitutor.EMPTY, types)) { + if (MethodCallUtils.isApplicable(method, PsiSubstitutor.EMPTY, types)) { return false; } } diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/migration/unnecessary_boxing/Cast.after.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/migration/unnecessary_boxing/Cast.after.java new file mode 100644 index 000000000000..abc9403be8e0 --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/migration/unnecessary_boxing/Cast.after.java @@ -0,0 +1,7 @@ +package com.siyeh.igfixes.migration.unnecessary_boxing; + +class Cast { + Double foo(String s) { + return (double) (s.isEmpty() ? 1 : 2); + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/migration/unnecessary_boxing/Cast.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/migration/unnecessary_boxing/Cast.java new file mode 100644 index 000000000000..4df9ce450f22 --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/migration/unnecessary_boxing/Cast.java @@ -0,0 +1,7 @@ +package com.siyeh.igfixes.migration.unnecessary_boxing; + +class Cast { + Double foo(String s) { + return new Double(s.isEmpty() ? 1 : 2); + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/stringBuffer_stringBuilder/CallChain.after.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/stringBuffer_stringBuilder/CallChain.after.java new file mode 100644 index 000000000000..3f2981a2b05a --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/stringBuffer_stringBuilder/CallChain.after.java @@ -0,0 +1,6 @@ +class Test { + String foo() { + StringBuilder sb = new StringBuilder().append("a").append("|").append("b"); + return sb.toString(); + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/stringBuffer_stringBuilder/CallChain.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/stringBuffer_stringBuilder/CallChain.java new file mode 100644 index 000000000000..36ff6b974278 --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/stringBuffer_stringBuilder/CallChain.java @@ -0,0 +1,6 @@ +class Test { + String foo() { + StringBuffer sb = new StringBuffer().append("a").append("|").append("b"); + return sb.toString(); + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/migration/UnnecessaryBoxingFixTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/migration/UnnecessaryBoxingFixTest.java new file mode 100644 index 000000000000..e974441c5060 --- /dev/null +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/migration/UnnecessaryBoxingFixTest.java @@ -0,0 +1,27 @@ +package com.siyeh.ig.fixes.migration; + +import com.siyeh.InspectionGadgetsBundle; +import com.siyeh.ig.IGQuickFixesTestCase; +import com.siyeh.ig.migration.UnnecessaryBoxingInspection; + +public class UnnecessaryBoxingFixTest extends IGQuickFixesTestCase { + + @Override + protected void setUp() throws Exception { + super.setUp(); + myFixture.enableInspections(new UnnecessaryBoxingInspection()); + } + + public void testCast() { + doFixTest(); + } + + private void doFixTest() { + doTest(getTestName(true), InspectionGadgetsBundle.message("unnecessary.boxing.remove.quickfix")); + } + + @Override + protected String getRelativePath() { + return "migration/unnecessary_boxing"; + } +} \ No newline at end of file diff --git a/plugins/android-designer/src/com/intellij/android/designer/propertyTable/editors/BooleanEditor.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/migration/StringBufferReplaceableByStringBuilderInspectionTest.java similarity index 51% rename from plugins/android-designer/src/com/intellij/android/designer/propertyTable/editors/BooleanEditor.java rename to plugins/InspectionGadgets/testsrc/com/siyeh/ig/migration/StringBufferReplaceableByStringBuilderInspectionTest.java index ba21dcd2c6d6..2aca65ad5483 100644 --- a/plugins/android-designer/src/com/intellij/android/designer/propertyTable/editors/BooleanEditor.java +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/migration/StringBufferReplaceableByStringBuilderInspectionTest.java @@ -13,21 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.intellij.android.designer.propertyTable.editors; +package com.siyeh.ig.migration; -import com.intellij.openapi.util.text.StringUtil; +import com.siyeh.InspectionGadgetsBundle; +import com.siyeh.ig.IGQuickFixesTestCase; -/** - * @author Alexander Lobas - */ -public class BooleanEditor extends com.intellij.designer.propertyTable.editors.BooleanEditor { +public class StringBufferReplaceableByStringBuilderInspectionTest extends IGQuickFixesTestCase { @Override - public Object getValue() throws Exception { - return Boolean.toString(myCheckBox.isSelected()); + public void setUp() throws Exception { + super.setUp(); + myFixture.enableInspections(new StringBufferReplaceableByStringBuilderInspection()); + myRelativePath = "stringBuffer_stringBuilder"; + myDefaultHint = InspectionGadgetsBundle.message("string.buffer.replaceable.by.string.builder.replace.quickfix"); } - @Override - protected boolean getValue(Object value) { - return Boolean.parseBoolean((String)value); + public void testCallChain() { + doTest(); } -} \ No newline at end of file +} diff --git a/plugins/android-designer/src/com/intellij/android/designer/designSurface/ExternalPSIChangeListener.java b/plugins/android-designer/src/com/intellij/android/designer/designSurface/ExternalPSIChangeListener.java index 601cca10860a..27050d13a41e 100644 --- a/plugins/android-designer/src/com/intellij/android/designer/designSurface/ExternalPSIChangeListener.java +++ b/plugins/android-designer/src/com/intellij/android/designer/designSurface/ExternalPSIChangeListener.java @@ -18,6 +18,7 @@ package com.intellij.android.designer.designSurface; import com.intellij.openapi.application.ModalityState; import com.intellij.psi.*; import com.intellij.util.Alarm; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -84,32 +85,32 @@ public class ExternalPSIChangeListener extends PsiTreeChangeAdapter { ////////////////////////////////////////////////////////////////////////////////////////// @Override - public void childAdded(PsiTreeChangeEvent event) { + public void childAdded(@NotNull PsiTreeChangeEvent event) { updatePsi(event); } @Override - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { updatePsi(event); } @Override - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { updatePsi(event); } @Override - public void childMoved(PsiTreeChangeEvent event) { + public void childMoved(@NotNull PsiTreeChangeEvent event) { updatePsi(event); } @Override - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { updatePsi(event); } @Override - public void propertyChanged(PsiTreeChangeEvent event) { + public void propertyChanged(@NotNull PsiTreeChangeEvent event) { updatePsi(event); } } \ No newline at end of file diff --git a/plugins/android-designer/src/com/intellij/android/designer/model/PropertyParser.java b/plugins/android-designer/src/com/intellij/android/designer/model/PropertyParser.java index 9e8ad8fc9e2d..a318de28dba5 100644 --- a/plugins/android-designer/src/com/intellij/android/designer/model/PropertyParser.java +++ b/plugins/android-designer/src/com/intellij/android/designer/model/PropertyParser.java @@ -173,7 +173,7 @@ public class PropertyParser { } @NotNull - public ResourceDialog createResourceDialog(ResourceType... types) { + public ResourceDialog createResourceDialog(ResourceType[] types) { return new ResourceDialog(myModule, types); } } \ No newline at end of file diff --git a/plugins/android-designer/src/com/intellij/android/designer/propertyTable/AttributeProperty.java b/plugins/android-designer/src/com/intellij/android/designer/propertyTable/AttributeProperty.java index 356fda1dfcc9..31df0818b22c 100644 --- a/plugins/android-designer/src/com/intellij/android/designer/propertyTable/AttributeProperty.java +++ b/plugins/android-designer/src/com/intellij/android/designer/propertyTable/AttributeProperty.java @@ -15,22 +15,16 @@ */ package com.intellij.android.designer.propertyTable; -import com.android.resources.ResourceType; -import com.intellij.android.designer.model.PropertyParser; import com.intellij.android.designer.model.RadViewComponent; -import com.intellij.android.designer.propertyTable.editors.BooleanEditor; -import com.intellij.android.designer.propertyTable.editors.ResourceDialog; +import com.intellij.android.designer.propertyTable.editors.ResourceEditor; import com.intellij.android.designer.propertyTable.editors.StringsComboEditor; -import com.intellij.android.designer.propertyTable.renderers.BooleanRenderer; -import com.intellij.designer.model.RadComponent; +import com.intellij.android.designer.propertyTable.renderers.ResourceRenderer; import com.intellij.designer.propertyTable.Property; import com.intellij.designer.propertyTable.PropertyEditor; import com.intellij.designer.propertyTable.PropertyRenderer; import com.intellij.designer.propertyTable.editors.AbstractTextFieldEditor; import com.intellij.designer.propertyTable.renderers.LabelPropertyRenderer; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.ui.DialogWrapper; -import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.xml.XmlAttribute; import org.jetbrains.android.dom.attrs.AttributeDefinition; @@ -38,9 +32,6 @@ import org.jetbrains.android.dom.attrs.AttributeFormat; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.swing.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.Set; /** @@ -56,20 +47,10 @@ public class AttributeProperty extends Property { myDefinition = definition; Set formats = definition.getFormats(); - if (formats.contains(AttributeFormat.Boolean)) { - myRenderer = new BooleanRenderer(); - myEditor = new BooleanEditor(); - } - else { - myRenderer = new LabelPropertyRenderer(null); - if (formats.contains(AttributeFormat.Enum)) { - myEditor = new StringsComboEditor(definition.getValues()); - } - else if (formats.contains(AttributeFormat.Reference)) { - myEditor = new TextDialogEditor(); - } - else { + if (formats.size() == 1) { + if (formats.contains(AttributeFormat.Float)) { + myRenderer = new LabelPropertyRenderer(null); myEditor = new AbstractTextFieldEditor() { @Override public Object getValue() throws Exception { @@ -77,6 +58,18 @@ public class AttributeProperty extends Property { } }; } + else if (formats.contains(AttributeFormat.Enum)) { + myRenderer = new LabelPropertyRenderer(null); + myEditor = new StringsComboEditor(definition.getValues()); + } + else { + myRenderer = new ResourceRenderer(formats); + myEditor = new ResourceEditor(formats, definition.getValues()); + } + } + else { + myRenderer = new ResourceRenderer(formats); + myEditor = new ResourceEditor(formats, definition.getValues()); } } @@ -142,47 +135,4 @@ public class AttributeProperty extends Property { public PropertyEditor getEditor() { return myEditor; } - - private static class TextDialogEditor extends PropertyEditor { - private TextFieldWithBrowseButton myTextField; - private RadComponent myRootComponent; - - public TextDialogEditor() { - myTextField = new TextFieldWithBrowseButton(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - PropertyParser parser = myRootComponent.getClientProperty(PropertyParser.KEY); - ResourceDialog dialog = parser - .createResourceDialog(ResourceType.BOOL, ResourceType.COLOR, ResourceType.DIMEN, ResourceType.DRAWABLE, ResourceType.INTEGER, - ResourceType.STRING, ResourceType.ID); - dialog.show(); - - if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) { - myTextField.setText(dialog.getResourceName()); - fireValueCommitted(true, false); - } - } - }); - myTextField.getTextField().setBorder(null); - } - - @NotNull - @Override - public JComponent getComponent(@NotNull RadComponent rootComponent, @Nullable RadComponent component, Object value) { - myRootComponent = rootComponent; - myTextField.setText(value == null ? "" : value.toString()); - myTextField.getTextField().setBorder(null); - return myTextField; - } - - @Override - public Object getValue() throws Exception { - return myTextField.getText(); - } - - @Override - public void updateUI() { - SwingUtilities.updateComponentTreeUI(myTextField); - } - } } \ No newline at end of file diff --git a/plugins/android-designer/src/com/intellij/android/designer/propertyTable/editors/ResourceEditor.java b/plugins/android-designer/src/com/intellij/android/designer/propertyTable/editors/ResourceEditor.java new file mode 100644 index 000000000000..1b22c07a6ed4 --- /dev/null +++ b/plugins/android-designer/src/com/intellij/android/designer/propertyTable/editors/ResourceEditor.java @@ -0,0 +1,161 @@ +/* + * 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.android.designer.propertyTable.editors; + +import com.android.resources.ResourceType; +import com.intellij.android.designer.model.PropertyParser; +import com.intellij.designer.model.RadComponent; +import com.intellij.designer.propertyTable.PropertyEditor; +import com.intellij.designer.propertyTable.editors.ComboEditor; +import com.intellij.openapi.ui.ComponentWithBrowseButton; +import com.intellij.openapi.ui.DialogWrapper; +import com.intellij.openapi.ui.TextFieldWithBrowseButton; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.ui.ComboboxWithBrowseButton; +import org.jetbrains.android.dom.attrs.AttributeFormat; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import java.awt.event.*; +import java.util.EnumSet; +import java.util.Set; + +/** + * @author Alexander Lobas + */ +public class ResourceEditor extends PropertyEditor { + private ResourceType[] myTypes; + private ComponentWithBrowseButton myEditor; + private RadComponent myRootComponent; + + public ResourceEditor(Set formats, String[] values) { + Set types = EnumSet.noneOf(ResourceType.class); + for (AttributeFormat format : formats) { + switch (format) { + case Boolean: + types.add(ResourceType.BOOL); + break; + case Color: + types.add(ResourceType.COLOR); + types.add(ResourceType.DRAWABLE); + break; + case Dimension: + types.add(ResourceType.DIMEN); + break; + case Integer: + types.add(ResourceType.INTEGER); + break; + case String: + types.add(ResourceType.STRING); + break; + case Reference: + types.add(ResourceType.COLOR); + types.add(ResourceType.DRAWABLE); + types.add(ResourceType.STRING); + types.add(ResourceType.ID); + types.add(ResourceType.STYLE); + break; + } + } + myTypes = types.toArray(new ResourceType[types.size()]); + + if (formats.contains(AttributeFormat.Enum) || formats.contains(AttributeFormat.Boolean)) { + ComboboxWithBrowseButton editor = new ComboboxWithBrowseButton(); + + final JComboBox comboBox = editor.getComboBox(); + DefaultComboBoxModel model; + if (formats.contains(AttributeFormat.Boolean)) { + model = new DefaultComboBoxModel(new String[]{StringsComboEditor.UNSET, "true", "false"}); + } + else { + model = new DefaultComboBoxModel(values); + model.insertElementAt(StringsComboEditor.UNSET, 0); + } + comboBox.setModel(model); + comboBox.setEditable(true); + ComboEditor.addEditorSupport(this, comboBox); + comboBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (comboBox.getSelectedItem() == StringsComboEditor.UNSET) { + comboBox.setSelectedItem(null); + } + fireValueCommitted(true, true); + } + }); + myEditor = editor; + comboBox.setSelectedIndex(0); + } + else { + myEditor = new TextFieldWithBrowseButton(); + myEditor.registerKeyboardAction(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + } + }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + } + + myEditor.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + PropertyParser parser = myRootComponent.getClientProperty(PropertyParser.KEY); + ResourceDialog dialog = parser.createResourceDialog(myTypes); + dialog.show(); + + if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) { + getComboText().setText(dialog.getResourceName()); + fireValueCommitted(true, true); + } + } + }); + myEditor.addFocusListener(new FocusAdapter() { + @Override + public void focusGained(FocusEvent e) { + myEditor.getChildComponent().requestFocus(); + } + }); + } + + @NotNull + @Override + public JComponent getComponent(@NotNull RadComponent rootComponent, @Nullable RadComponent component, Object value) { + myRootComponent = rootComponent; + JTextField text = getComboText(); + text.setText((String)value); + return myEditor; + } + + @Override + public Object getValue() throws Exception { + String value = getComboText().getText(); + return value == StringsComboEditor.UNSET || StringUtil.isEmpty(value) ? null : value; + } + + private JTextField getComboText() { + JComponent component = myEditor.getChildComponent(); + if (component instanceof JTextField) { + return (JTextField)component; + } + JComboBox combo = (JComboBox)component; + return (JTextField)combo.getEditor().getEditorComponent(); + } + + @Override + public void updateUI() { + SwingUtilities.updateComponentTreeUI(myEditor); + } +} \ No newline at end of file diff --git a/plugins/android-designer/src/com/intellij/android/designer/propertyTable/editors/StringsComboEditor.java b/plugins/android-designer/src/com/intellij/android/designer/propertyTable/editors/StringsComboEditor.java index 8028c3f5e0d4..0cff35b05c96 100644 --- a/plugins/android-designer/src/com/intellij/android/designer/propertyTable/editors/StringsComboEditor.java +++ b/plugins/android-designer/src/com/intellij/android/designer/propertyTable/editors/StringsComboEditor.java @@ -16,18 +16,40 @@ package com.intellij.android.designer.propertyTable.editors; import com.intellij.designer.model.RadComponent; +import com.intellij.designer.propertyTable.PropertyEditor; import com.intellij.designer.propertyTable.editors.ComboEditor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; +import java.awt.event.ActionEvent; /** * @author Alexander Lobas */ public class StringsComboEditor extends ComboEditor { + public static final String UNSET = ""; + public StringsComboEditor(String[] values) { - myCombo.setModel(new DefaultComboBoxModel(values)); + DefaultComboBoxModel model = new DefaultComboBoxModel(values); + model.insertElementAt(UNSET, 0); + myCombo.setModel(model); + myCombo.addActionListener(new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + if (myCombo.getSelectedItem() == UNSET) { + myCombo.setSelectedItem(null); + } + } + }); + + myCombo.setSelectedIndex(0); + } + + @Override + public Object getValue() throws Exception { + Object item = myCombo.getSelectedItem(); + return item == UNSET ? null : item; } @NotNull @@ -36,9 +58,4 @@ public class StringsComboEditor extends ComboEditor { myCombo.setSelectedItem(value); return myCombo; } - - @Override - public Object getValue() throws Exception { - return myCombo.getSelectedItem(); - } } \ No newline at end of file diff --git a/plugins/android-designer/src/com/intellij/android/designer/propertyTable/renderers/ResourceRenderer.java b/plugins/android-designer/src/com/intellij/android/designer/propertyTable/renderers/ResourceRenderer.java new file mode 100644 index 000000000000..2fa9cc54c32e --- /dev/null +++ b/plugins/android-designer/src/com/intellij/android/designer/propertyTable/renderers/ResourceRenderer.java @@ -0,0 +1,161 @@ +/* + * 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.android.designer.propertyTable.renderers; + +import com.intellij.designer.model.RadComponent; +import com.intellij.designer.propertyTable.PropertyRenderer; +import com.intellij.designer.propertyTable.renderers.BooleanRenderer; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.ui.SimpleColoredComponent; +import com.intellij.ui.SimpleTextAttributes; +import com.intellij.util.ArrayUtil; +import com.intellij.util.ui.EmptyIcon; +import com.intellij.util.ui.UIUtil; +import org.jetbrains.android.dom.attrs.AttributeFormat; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import java.awt.*; +import java.util.Set; + +/** + * @author Alexander Lobas + */ +public class ResourceRenderer implements PropertyRenderer { + private static final String[] DIMENSIONS = {"dp", "sp", "pt", "px", "mm", "in"}; + private static final String ANDROID_PREFIX = "@android:"; + + private final ColorIcon myColorIcon = new ColorIcon(10, 9); + private BooleanRenderer myBooleanRenderer; + private final SimpleColoredComponent myColoredComponent; + private final Set myFormats; + + public ResourceRenderer(Set formats) { + if (formats.contains(AttributeFormat.Boolean)) { + myBooleanRenderer = new BooleanRenderer(); + } + + myColoredComponent = new SimpleColoredComponent(); + + myFormats = formats; + } + + @NotNull + @Override + public JComponent getComponent(@Nullable RadComponent component, @Nullable Object object, boolean selected, boolean hasFocus) { + String value = (String)object; + + if (myBooleanRenderer != null && (StringUtil.isEmpty(value) || "false".equals(value) || "true".equals(value))) { + return myBooleanRenderer.getComponent(component, "true".equals(value), selected, hasFocus); + } + + myColoredComponent.clear(); + + if (selected) { + myColoredComponent.setForeground(UIUtil.getTableSelectionForeground()); + Color background = UIUtil.getTableSelectionBackground(); + myColoredComponent.setBackground(background); + } + else { + myColoredComponent.setForeground(UIUtil.getTableForeground()); + myColoredComponent.setBackground(UIUtil.getTableBackground()); + } + + if (!StringUtil.isEmpty(value)) { + int prefix = -1; + if (value.startsWith("#")) { + prefix = 1; + } + else if (value.startsWith(ANDROID_PREFIX)) { + prefix = ANDROID_PREFIX.length(); + } + else if (value.startsWith("@")) { + prefix = 1; + } + if (prefix != -1) { + myColoredComponent.append(value.substring(0, prefix), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); + myColoredComponent.append(value.substring(prefix)); + } + else if (myFormats.contains(AttributeFormat.Dimension) && value.length() > 2) { + int index = value.length() - 2; + String dimension = value.substring(index); + if (ArrayUtil.indexOf(DIMENSIONS, dimension) != -1) { + myColoredComponent.append(value.substring(0, index)); + myColoredComponent.append(dimension, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); + } + else { + myColoredComponent.append(value); + } + } + else { + myColoredComponent.append(value); + } + if (myFormats.contains(AttributeFormat.Color) && value.startsWith("#")) { + try { + myColorIcon.setColor(new Color(Integer.parseInt(value.substring(1), 16))); + myColoredComponent.setIcon(myColorIcon); + } + catch (Throwable e) { + } + } + } + + return myColoredComponent; + } + + @Override + public void updateUI() { + if (myBooleanRenderer != null) { + SwingUtilities.updateComponentTreeUI(myBooleanRenderer); + } + SwingUtilities.updateComponentTreeUI(myColoredComponent); + } + + private static class ColorIcon extends EmptyIcon { + private final int myColorSize; + private Color myColor; + + public ColorIcon(int size, int colorSize) { + super(size, size); + myColorSize = colorSize; + } + + public void setColor(Color color) { + myColor = color; + } + + @Override + public void paintIcon(Component component, Graphics g, final int left, final int top) { + int iconWidth = getIconWidth(); + int iconHeight = getIconHeight(); + + SimpleColoredComponent coloredComponent = (SimpleColoredComponent)component; + g.setColor(component.getBackground()); + g.fillRect(left - coloredComponent.getIpad().left, 0, + iconWidth + coloredComponent.getIpad().left + coloredComponent.getIconTextGap(), component.getHeight()); + + int x = left + (iconWidth - myColorSize) / 2; + int y = top + (iconHeight - myColorSize) / 2; + + g.setColor(myColor); + g.fillRect(x, y, myColorSize, myColorSize); + + g.setColor(Color.BLACK); + g.drawRect(x, y, myColorSize, myColorSize); + } + } +} \ No newline at end of file diff --git a/plugins/android/android.iml b/plugins/android/android.iml index 348cd17b2c7d..9da7d4398eb8 100644 --- a/plugins/android/android.iml +++ b/plugins/android/android.iml @@ -62,6 +62,7 @@ +
diff --git a/plugins/android/common/android-common.iml b/plugins/android/common/android-common.iml new file mode 100644 index 000000000000..4e8e59de5816 --- /dev/null +++ b/plugins/android/common/android-common.iml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidApkBuilder.java b/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidApkBuilder.java similarity index 99% rename from plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidApkBuilder.java rename to plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidApkBuilder.java index 70daf97f8e74..9465c698cfe2 100644 --- a/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidApkBuilder.java +++ b/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidApkBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 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. diff --git a/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidApt.java b/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidApt.java similarity index 99% rename from plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidApt.java rename to plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidApt.java index 19bf21739f52..4457646134b1 100644 --- a/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidApt.java +++ b/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidApt.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 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. diff --git a/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidIdl.java b/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidIdl.java similarity index 98% rename from plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidIdl.java rename to plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidIdl.java index 90f4faec384d..12dc0a97e293 100644 --- a/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidIdl.java +++ b/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidIdl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 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. diff --git a/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidRenderscript.java b/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidRenderscript.java similarity index 80% rename from plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidRenderscript.java rename to plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidRenderscript.java index b3346c8401d5..0b7a523b9f32 100644 --- a/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidRenderscript.java +++ b/plugins/android/common/src/org/jetbrains/android/compiler/tools/AndroidRenderscript.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. + */ package org.jetbrains.android.compiler.tools; import com.android.sdklib.IAndroidTarget; diff --git a/plugins/android/rt/src/org/jetbrains/android/sdk/MessageBuildingSdkLog.java b/plugins/android/common/src/org/jetbrains/android/sdk/MessageBuildingSdkLog.java similarity index 97% rename from plugins/android/rt/src/org/jetbrains/android/sdk/MessageBuildingSdkLog.java rename to plugins/android/common/src/org/jetbrains/android/sdk/MessageBuildingSdkLog.java index 49e083d10236..040211d7e23b 100644 --- a/plugins/android/rt/src/org/jetbrains/android/sdk/MessageBuildingSdkLog.java +++ b/plugins/android/common/src/org/jetbrains/android/sdk/MessageBuildingSdkLog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 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. diff --git a/plugins/android/rt/src/org/jetbrains/android/util/AndroidCommonUtils.java b/plugins/android/common/src/org/jetbrains/android/util/AndroidCommonUtils.java similarity index 95% rename from plugins/android/rt/src/org/jetbrains/android/util/AndroidCommonUtils.java rename to plugins/android/common/src/org/jetbrains/android/util/AndroidCommonUtils.java index 52163c045387..78d50b0566ce 100644 --- a/plugins/android/rt/src/org/jetbrains/android/util/AndroidCommonUtils.java +++ b/plugins/android/common/src/org/jetbrains/android/util/AndroidCommonUtils.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. + */ package org.jetbrains.android.util; import com.android.resources.ResourceFolderType; diff --git a/plugins/android-designer/src/com/intellij/android/designer/propertyTable/renderers/BooleanRenderer.java b/plugins/android/common/src/org/jetbrains/android/util/AndroidCompilerMessageKind.java similarity index 66% rename from plugins/android-designer/src/com/intellij/android/designer/propertyTable/renderers/BooleanRenderer.java rename to plugins/android/common/src/org/jetbrains/android/util/AndroidCompilerMessageKind.java index 61adcd26ebb1..677a75bcc0c2 100644 --- a/plugins/android-designer/src/com/intellij/android/designer/propertyTable/renderers/BooleanRenderer.java +++ b/plugins/android/common/src/org/jetbrains/android/util/AndroidCompilerMessageKind.java @@ -13,14 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.intellij.android.designer.propertyTable.renderers; +package org.jetbrains.android.util; /** - * @author Alexander Lobas + * @author Eugene.Kudelevsky */ -public class BooleanRenderer extends com.intellij.designer.propertyTable.renderers.BooleanRenderer { - @Override - protected boolean getValue(Object value) { - return Boolean.parseBoolean((String)value); - } -} \ No newline at end of file +public enum AndroidCompilerMessageKind { + ERROR, INFORMATION, WARNING +} diff --git a/plugins/android/rt/src/org/jetbrains/android/util/AndroidExecutionUtil.java b/plugins/android/common/src/org/jetbrains/android/util/AndroidExecutionUtil.java similarity index 98% rename from plugins/android/rt/src/org/jetbrains/android/util/AndroidExecutionUtil.java rename to plugins/android/common/src/org/jetbrains/android/util/AndroidExecutionUtil.java index e871048b6871..6d56b9a65671 100644 --- a/plugins/android/rt/src/org/jetbrains/android/util/AndroidExecutionUtil.java +++ b/plugins/android/common/src/org/jetbrains/android/util/AndroidExecutionUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 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. diff --git a/plugins/android/rt/src/org/jetbrains/android/util/AndroidOSProcessHandler.java b/plugins/android/common/src/org/jetbrains/android/util/AndroidOSProcessHandler.java similarity index 74% rename from plugins/android/rt/src/org/jetbrains/android/util/AndroidOSProcessHandler.java rename to plugins/android/common/src/org/jetbrains/android/util/AndroidOSProcessHandler.java index 1811d0e24fc7..4a48d0687d9a 100644 --- a/plugins/android/rt/src/org/jetbrains/android/util/AndroidOSProcessHandler.java +++ b/plugins/android/common/src/org/jetbrains/android/util/AndroidOSProcessHandler.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. + */ package org.jetbrains.android.util; import com.intellij.execution.process.BaseOSProcessHandler; diff --git a/plugins/android/rt/src/org/jetbrains/android/util/ResourceEntry.java b/plugins/android/common/src/org/jetbrains/android/util/ResourceEntry.java similarity index 60% rename from plugins/android/rt/src/org/jetbrains/android/util/ResourceEntry.java rename to plugins/android/common/src/org/jetbrains/android/util/ResourceEntry.java index c9fbe72541fa..af49933d48ad 100644 --- a/plugins/android/rt/src/org/jetbrains/android/util/ResourceEntry.java +++ b/plugins/android/common/src/org/jetbrains/android/util/ResourceEntry.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. + */ package org.jetbrains.android.util; import org.jetbrains.annotations.NotNull; diff --git a/plugins/android/rt/src/org/jetbrains/android/util/ValueResourcesFileParser.java b/plugins/android/common/src/org/jetbrains/android/util/ValueResourcesFileParser.java similarity index 79% rename from plugins/android/rt/src/org/jetbrains/android/util/ValueResourcesFileParser.java rename to plugins/android/common/src/org/jetbrains/android/util/ValueResourcesFileParser.java index 240271a0027f..fb260ad45ca3 100644 --- a/plugins/android/rt/src/org/jetbrains/android/util/ValueResourcesFileParser.java +++ b/plugins/android/common/src/org/jetbrains/android/util/ValueResourcesFileParser.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. + */ package org.jetbrains.android.util; import com.android.resources.ResourceType; diff --git a/plugins/android/jps-plugin/android-jps-plugin.iml b/plugins/android/jps-plugin/android-jps-plugin.iml index f88dae99cac0..7177beeceb26 100644 --- a/plugins/android/jps-plugin/android-jps-plugin.iml +++ b/plugins/android/jps-plugin/android-jps-plugin.iml @@ -9,6 +9,7 @@ + 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 62c00c78e32b..85359ccb62c9 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 @@ -1,9 +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. + */ package org.jetbrains.jps.android; import com.android.sdklib.IAndroidTarget; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.HashMap; import com.intellij.util.containers.HashSet; @@ -217,7 +233,7 @@ public class AndroidDexBuilder extends ProjectLevelBuilder { final List classPath = new ArrayList(); classPath.add(ClasspathBootstrap.getResourcePath(AndroidDxRunner.class).getPath()); - classPath.add(ClasspathBootstrap.getResourcePath(FileUtil.class).getPath()); + classPath.add(ClasspathBootstrap.getResourcePath(FileUtilRt.class).getPath()); final File outFile = new File(outFilePath); if (outFile.exists() && !outFile.delete()) { diff --git a/plugins/android/rt/android-rt.iml b/plugins/android/rt/android-rt.iml index a45948b193fb..7e88b0067116 100644 --- a/plugins/android/rt/android-rt.iml +++ b/plugins/android/rt/android-rt.iml @@ -4,29 +4,11 @@ - - - - - - - - - - - - - - - - - - - - + +
diff --git a/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidDxRunner.java b/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidDxRunner.java index 93a1905e390c..017d393d6aab 100644 --- a/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidDxRunner.java +++ b/plugins/android/rt/src/org/jetbrains/android/compiler/tools/AndroidDxRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 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. @@ -15,7 +15,7 @@ */ package org.jetbrains.android.compiler.tools; -import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.util.io.FileUtilRt; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; @@ -56,8 +56,7 @@ public class AndroidDxRunner { private static Field myConsoleOut; private static Field myConsoleErr; - private AndroidDxRunner() { - } + private AndroidDxRunner() { } private static void loadDex(String dxPath) { try { @@ -166,10 +165,10 @@ public class AndroidDxRunner { } } else { - if ("class".equals(FileUtil.getExtension(file.getName()))) { + if ("class".equals(FileUtilRt.getExtension(file.getName()))) { final String qName = getQualifiedName(root, file); if (qName != null && !qNames.add(qName)) { - reportWarning(FileUtil.toSystemDependentName(file.getPath()) + " won't be added. Class " + + reportWarning(FileUtilRt.toSystemDependentName(file.getPath()) + " won't be added. Class " + qName + " already exists in classpath"); return; } @@ -180,12 +179,12 @@ public class AndroidDxRunner { @Nullable private static String getQualifiedName(File root, File classFile) { - String relativePath = FileUtil.getRelativePath(root, classFile); + String relativePath = FileUtilRt.getRelativePath(root, classFile); if (relativePath == null) { return null; } - return FileUtil.getNameWithoutExtension(FileUtil.toSystemIndependentName(relativePath)).replace('/', '.'); + return FileUtilRt.getNameWithoutExtension(FileUtilRt.toSystemIndependentName(relativePath)).replace('/', '.'); } public static void main(String[] args) { diff --git a/plugins/android/rt/src/org/jetbrains/android/util/AndroidCompilerMessageKind.java b/plugins/android/rt/src/org/jetbrains/android/util/AndroidCompilerMessageKind.java deleted file mode 100644 index 6c8a8cb80c50..000000000000 --- a/plugins/android/rt/src/org/jetbrains/android/util/AndroidCompilerMessageKind.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.jetbrains.android.util; - -/** - * @author Eugene.Kudelevsky - */ -public enum AndroidCompilerMessageKind { - ERROR, INFORMATION, WARNING -} diff --git a/plugins/android/src/META-INF/plugin.xml b/plugins/android/src/META-INF/plugin.xml index 008774bdaad1..bdb604995847 100644 --- a/plugins/android/src/META-INF/plugin.xml +++ b/plugins/android/src/META-INF/plugin.xml @@ -217,7 +217,7 @@ - + diff --git a/plugins/android/src/org/jetbrains/android/compiler/tools/AndroidDxWrapper.java b/plugins/android/src/org/jetbrains/android/compiler/tools/AndroidDxWrapper.java index 3de13461b4bc..892ff18591ea 100644 --- a/plugins/android/src/org/jetbrains/android/compiler/tools/AndroidDxWrapper.java +++ b/plugins/android/src/org/jetbrains/android/compiler/tools/AndroidDxWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 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. @@ -25,7 +25,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootManager; -import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.util.PathUtil; import com.intellij.util.PathsList; import com.intellij.util.containers.HashMap; @@ -97,7 +97,7 @@ public class AndroidDxWrapper { } final PathsList classPath = parameters.getClassPath(); classPath.add(PathUtil.getJarPathForClass(AndroidDxRunner.class)); - classPath.add(PathUtil.getJarPathForClass(FileUtil.class)); + classPath.add(PathUtil.getJarPathForClass(FileUtilRt.class)); // delete file to check if it will exist after dex compilation if (!new File(outFile).delete()) { diff --git a/plugins/android/src/org/jetbrains/android/uipreview/AndroidLayoutPreviewToolWindowManager.java b/plugins/android/src/org/jetbrains/android/uipreview/AndroidLayoutPreviewToolWindowManager.java index 149829c9fb2c..9242541761d9 100644 --- a/plugins/android/src/org/jetbrains/android/uipreview/AndroidLayoutPreviewToolWindowManager.java +++ b/plugins/android/src/org/jetbrains/android/uipreview/AndroidLayoutPreviewToolWindowManager.java @@ -112,19 +112,19 @@ public class AndroidLayoutPreviewToolWindowManager implements ProjectComponent { }); PsiManager.getInstance(project).addPsiTreeChangeListener(new PsiTreeChangeAdapter() { - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { update(event); } - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { update(event); } - public void childAdded(PsiTreeChangeEvent event) { + public void childAdded(@NotNull PsiTreeChangeEvent event) { update(event); } - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { update(event); } }, project); diff --git a/plugins/git4idea/src/org/jetbrains/git4idea/util/ScriptGenerator.java b/plugins/git4idea/src/org/jetbrains/git4idea/util/ScriptGenerator.java index ffdb80c526cd..6c6b6011e59a 100644 --- a/plugins/git4idea/src/org/jetbrains/git4idea/util/ScriptGenerator.java +++ b/plugins/git4idea/src/org/jetbrains/git4idea/util/ScriptGenerator.java @@ -17,11 +17,11 @@ package org.jetbrains.git4idea.util; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.util.SystemInfo; +import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; -import com.intellij.openapi.util.io.FileUtilRt; import java.io.File; import java.io.FileWriter; @@ -149,8 +149,8 @@ public class ScriptGenerator { */ @SuppressWarnings({"HardCodedStringLiteral"}) public File generate() throws IOException { - File scriptPath = myTempDir != null ? FileUtilRt.createTempFile(myTempDir, myPrefix, SCRIPT_EXT, true) - : FileUtilRt.createTempFile(myPrefix, SCRIPT_EXT); + File scriptPath = myTempDir != null ? FileUtil.createTempFile(myTempDir, myPrefix, SCRIPT_EXT, true) + : FileUtil.createTempFile(myPrefix, SCRIPT_EXT); scriptPath.deleteOnExit(); PrintWriter out = new PrintWriter(new FileWriter(scriptPath)); try { @@ -172,7 +172,7 @@ public class ScriptGenerator { finally { out.close(); } - FileUtilRt.setExecutableAttribute(scriptPath.getPath(), true); + FileUtil.setExecutableAttribute(scriptPath.getPath(), true); return scriptPath; } diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/remote/GradleApiFacadeManager.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/remote/GradleApiFacadeManager.java index 9994b4c74bdf..4aa461a2adc7 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/remote/GradleApiFacadeManager.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/remote/GradleApiFacadeManager.java @@ -28,7 +28,6 @@ import com.intellij.util.Alarm; import com.intellij.util.PathUtil; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ContainerUtil; -import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.gradle.notification.GradleProgressNotificationManager; import org.jetbrains.plugins.gradle.notification.GradleProgressNotificationManagerImpl; @@ -48,6 +47,7 @@ import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; @@ -122,10 +122,8 @@ public class GradleApiFacadeManager { params.setJdk(new SimpleJavaSdkType().createJdk("tmp", SystemProperties.getJavaHome())); params.setWorkingDirectory(PathManager.getBinPath()); - final ArrayList classPath = new ArrayList(); - ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(NotNull.class), classPath); - ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(StringUtil.class), classPath); - ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(THashSet.class), classPath); + final List classPath = new ArrayList(); + classPath.addAll(PathManager.getUtilClassPath()); ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(LanguageLevel.class), classPath); ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(PsiBundle.class), classPath); ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(Alarm.class), classPath); diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/psi/PsiEventsTest.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/psi/PsiEventsTest.java index d8cff6c77de1..e1965b0fddd6 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/psi/PsiEventsTest.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/psi/PsiEventsTest.java @@ -8,6 +8,7 @@ import com.intellij.openapi.util.Ref; import com.intellij.openapi.editor.Document; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.application.ApplicationManager; +import org.jetbrains.annotations.NotNull; /** * @author ven @@ -17,7 +18,7 @@ public class PsiEventsTest extends PsiTestCase { final Ref gotIt = new Ref(false); getPsiManager().addPsiTreeChangeListener(new PsiTreeChangeAdapter() { @Override - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { gotIt.set(true); } }); diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java index 9544f8611188..254ca383b648 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManagerWatcher.java @@ -212,11 +212,11 @@ public class MavenProjectsManagerWatcher { mySettingsFilesPointers.add( VirtualFilePointerManager.getInstance().create(url, myChangedDocumentsQueue, new VirtualFilePointerListener() { @Override - public void beforeValidityChanged(VirtualFilePointer[] pointers) { + public void beforeValidityChanged(@NotNull VirtualFilePointer[] pointers) { } @Override - public void validityChanged(VirtualFilePointer[] pointers) { + public void validityChanged(@NotNull VirtualFilePointer[] pointers) { } })); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java index d19ce28b6230..8c3d96ac7393 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java @@ -38,16 +38,14 @@ import com.intellij.openapi.projectRoots.SimpleJavaSdkType; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.ShutDownTracker; import com.intellij.openapi.util.SystemInfo; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Alarm; import com.intellij.util.PathUtil; import com.intellij.util.SmartList; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ContainerUtil; +import com.intellij.util.containers.ContainerUtilRt; import gnu.trove.THashMap; -import gnu.trove.THashSet; import org.apache.lucene.search.Query; -import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.maven.model.MavenId; @@ -58,7 +56,6 @@ import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenLog; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; import org.jetbrains.idea.maven.utils.MavenUtil; -import com.intellij.openapi.util.SystemInfoRt; import java.io.File; import java.nio.charset.Charset; @@ -170,12 +167,8 @@ public class MavenServerManager extends RemoteObjectWrapper { params.setJdk(new SimpleJavaSdkType().createJdk("tmp", SystemProperties.getJavaHome())); params.setWorkingDirectory(PathManager.getBinPath()); - final ArrayList classPath = new ArrayList(); - ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(NotNull.class), classPath); - ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(StringUtil.class), classPath); - ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(SystemInfoRt.class), classPath); - ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(THashSet.class), classPath); - ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(Element.class), classPath); + final List classPath = new ArrayList(); + classPath.addAll(PathManager.getUtilClassPath()); ContainerUtil.addIfNotNull(PathUtil.getJarPathForClass(Query.class), classPath); params.getClassPath().add(PathManager.getResourceRoot(getClass(), "/messages/CommonBundle.properties")); params.getClassPath().addAll(classPath); diff --git a/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleEditor.java b/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleEditor.java index dda560d2bbe3..78b8859f0af9 100644 --- a/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleEditor.java +++ b/plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleEditor.java @@ -270,23 +270,23 @@ public class ResourceBundleEditor extends UserDataHolderBase implements FileEdit virtualFileManager.addVirtualFileListener(myVfsListener, this); myPsiTreeChangeAdapter = new PsiTreeChangeAdapter() { - public void childAdded(PsiTreeChangeEvent event) { + public void childAdded(@NotNull PsiTreeChangeEvent event) { childrenChanged(event); } - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { childrenChanged(event); } - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { childrenChanged(event); } - public void childMoved(PsiTreeChangeEvent event) { + public void childMoved(@NotNull PsiTreeChangeEvent event) { childrenChanged(event); } - public void childrenChanged(PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull PsiTreeChangeEvent event) { final PsiFile file = event.getFile(); PropertiesFile propertiesFile = PropertiesUtil.getPropertiesFile(file); if (propertiesFile == null) return; diff --git a/plugins/spellchecker/src/com/intellij/spellchecker/english.dic b/plugins/spellchecker/src/com/intellij/spellchecker/english.dic index 8e1321bb6ff0..59e03e6c3ef0 100644 --- a/plugins/spellchecker/src/com/intellij/spellchecker/english.dic +++ b/plugins/spellchecker/src/com/intellij/spellchecker/english.dic @@ -134373,6 +134373,8 @@ veterinary veto veto's vetoed +vetoer +vetoers vetoes vetoing vets diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java index e89eb2ece0ce..934bba605fa1 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java @@ -20,6 +20,7 @@ import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.xml.sax.InputSource; import javax.swing.*; import java.io.InputStream; @@ -211,7 +212,9 @@ public class RedmineRepository extends BaseRepositoryImpl { } HttpMethod method = doREST(url, false); InputStream stream = method.getResponseBodyAsStream(); - Element element = new SAXBuilder(false).build(stream).getRootElement(); + InputSource source = new InputSource(stream); + source.setEncoding("UTF-8"); + Element element = new SAXBuilder(false).build(source).getRootElement(); if (!"issues".equals(element.getName())) { LOG.warn("Error fetching issues for: " + url + ", HTTP status code: " + method.getStatusCode()); diff --git a/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java b/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java index d44ccd594b57..e3e345f05a88 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java +++ b/plugins/testng/src/com/theoryinpractice/testng/configuration/SearchingForTestsTask.java @@ -240,6 +240,7 @@ public class SearchingForTestsTask extends Task.Backgroundable { return; } final Parser parser = new Parser(myData.getSuiteName()); + parser.setLoadClasses(false); final Collection suites = parser.parse(); for (XmlSuite suite : suites) { Map params = suite.getParameters(); diff --git a/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGVersionChecker.java b/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGVersionChecker.java index d43ade482b77..76c7e718bef7 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGVersionChecker.java +++ b/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGVersionChecker.java @@ -28,10 +28,7 @@ import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.updateSettings.impl.PluginDownloader; -import com.intellij.openapi.vfs.JarFileSystem; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.VirtualFileSystem; +import com.intellij.openapi.vfs.*; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiFile; @@ -63,39 +60,52 @@ public class TestNGVersionChecker { final PsiClass psiProtocolClass = JavaPsiFacade.getInstance(project).findClass(protocolClassMessageClass, scope); if (psiProtocolClass != null) { final String instanceFieldName = "m_instanceName"; + try { + final boolean userHasNewJar = psiProtocolClass.findFieldByName(instanceFieldName, false) != null; + + boolean ideaHasNewJar = true; + final Class aClass = Class.forName(protocolClassMessageClass); + try { + aClass.getDeclaredField(instanceFieldName); + } + catch (NoSuchFieldException e) { + ideaHasNewJar = false; + } + + if (userHasNewJar != ideaHasNewJar) { + return getIncompatibilityMessage(project, scope, pathToBundledJar); + } + } + catch (Exception ignore) { + } + } + return null; + } + + @Nullable + private static String getIncompatibilityMessage(Project project, GlobalSearchScope scope, String pathToBundledJar) { + final String protocolClassMessageClass = TestResultMessage.class.getName(); + final PsiClass psiProtocolClass = JavaPsiFacade.getInstance(project).findClass(protocolClassMessageClass, scope); + if (psiProtocolClass != null) { final ZipFile workingLibrary = getZipLibrary(project, scope); if (workingLibrary != null) { final VirtualFile bundledJar = LocalFileSystem.getInstance().findFileByPath(pathToBundledJar); if (bundledJar != null) { final String jarVersion = JarVersionDetectionUtil.detectJarVersion(workingLibrary); - final JarFileSystem jarFileSystem = JarFileSystem.getInstance(); - final VirtualFile bundledJarJar = jarFileSystem.getJarRootForLocalFile(bundledJar); + final VirtualFile bundledJarJar = JarFileSystem.getInstance().getJarRootForLocalFile(bundledJar); if (bundledJarJar == null) return null; String bundledVersion; try { - bundledVersion = JarVersionDetectionUtil.detectJarVersion(jarFileSystem.getJarFile(bundledJarJar)); + bundledVersion = JarVersionDetectionUtil.detectJarVersion(JarFileSystem.getInstance().getJarFile(bundledJarJar)); } catch (IOException e) { return null; } - final String incompatibilityMessage = TEST_NG_VERSIONS_INCOMPATIBILITY + - "Right now " + ApplicationNamesInfo.getInstance().getFullProductName() + - " does not support testng version (v." + jarVersion + ") used in your project due to the protocol changes on the TestNG side.
" + - "Bundled jar (v." + bundledVersion + ") was used instead to run your tests.
" + COPY_MESSAGE; - try { - final Class aClass = Class.forName(protocolClassMessageClass); - aClass.getDeclaredField(instanceFieldName); - if (psiProtocolClass.findFieldByName(instanceFieldName, false) == null) { - return incompatibilityMessage; - } - } - catch (NoSuchFieldException e) { - if (psiProtocolClass.findFieldByName(instanceFieldName, false) != null) { - return incompatibilityMessage; - } - } - catch (Exception ignore) { - } + return TEST_NG_VERSIONS_INCOMPATIBILITY + + "Right now " + ApplicationNamesInfo.getInstance().getFullProductName() + + " does not support testng version (v." + jarVersion + ") used in your project due to the protocol changes on the TestNG side.
" + + "Bundled jar (v." + bundledVersion + ") was used instead to run your tests.
" + + COPY_MESSAGE; } } } @@ -162,7 +172,7 @@ public class TestNGVersionChecker { if (library != null) { try { final String jarName = new File(PathUtil.getJarPathForClass(AfterClass.class)).getName(); - PluginDownloader.replaceLib(testNGPluginLibPath, jarName, library); + PluginDownloader.replaceLib(testNGPluginLibPath, jarName, VfsUtil.virtualToIoFile(library)); final Application app = ApplicationManager.getApplication(); final String updateSuccessfullyMessage = "Internal testng.jar was successfully updated. "; if (app.isRestartCapable()) { diff --git a/plugins/testng/src/com/theoryinpractice/testng/ui/TestNGResults.java b/plugins/testng/src/com/theoryinpractice/testng/ui/TestNGResults.java index e716620a4c32..925b9dabe92f 100644 --- a/plugins/testng/src/com/theoryinpractice/testng/ui/TestNGResults.java +++ b/plugins/testng/src/com/theoryinpractice/testng/ui/TestNGResults.java @@ -69,7 +69,7 @@ public class TestNGResults extends TestResultsPanel implements TestFrameworkRunn private final Project project; private int count; - private int total; + private int total = 0; private final Set failed = new HashSet(); private final Map> started = new HashMap>(); private TestProxy failedToStart = null; @@ -345,7 +345,7 @@ public class TestNGResults extends TestResultsPanel implements TestFrameworkRunn } public void setTotal(int total) { - this.total = total; + this.total += total; } public void start() { diff --git a/plugins/testng_rt/src/org/testng/RemoteTestNGStarter.java b/plugins/testng_rt/src/org/testng/RemoteTestNGStarter.java index 6c78b9e21541..0941a87b6325 100644 --- a/plugins/testng_rt/src/org/testng/RemoteTestNGStarter.java +++ b/plugins/testng_rt/src/org/testng/RemoteTestNGStarter.java @@ -74,6 +74,11 @@ public class RemoteTestNGStarter { if (line.startsWith(cantRunMessage) && !new File(line).exists()){ System.err.println(line.substring(cantRunMessage.length())); + while (true) { + line = reader.readLine(); + if (line == null || line.equals("end")) break; + System.err.println(line); + } System.exit(1); return; } diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GuiEditor.java b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GuiEditor.java index a25a990f7ad8..b19d46b823ac 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GuiEditor.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GuiEditor.java @@ -1077,27 +1077,27 @@ public final class GuiEditor extends JPanel implements DataProvider { myAlarm.cancelAllRequests(); } - public void childAdded(final PsiTreeChangeEvent event) { + public void childAdded(@NotNull final PsiTreeChangeEvent event) { handleEvent(event); } - public void childMoved(final PsiTreeChangeEvent event) { + public void childMoved(@NotNull final PsiTreeChangeEvent event) { handleEvent(event); } - public void childrenChanged(final PsiTreeChangeEvent event) { + public void childrenChanged(@NotNull final PsiTreeChangeEvent event) { handleEvent(event); } - public void childRemoved(PsiTreeChangeEvent event) { + public void childRemoved(@NotNull PsiTreeChangeEvent event) { handleEvent(event); } - public void childReplaced(PsiTreeChangeEvent event) { + public void childReplaced(@NotNull PsiTreeChangeEvent event) { handleEvent(event); } - public void propertyChanged(final PsiTreeChangeEvent event) { + public void propertyChanged(@NotNull final PsiTreeChangeEvent event) { if (PsiTreeChangeEvent.PROP_ROOTS.equals(event.getPropertyName())) { myAlarm.cancelRequest(myRefreshPropertiesRequest); myAlarm.addRequest(myRefreshPropertiesRequest, 500, ModalityState.stateForComponent(GuiEditor.this)); diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.java b/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.java index c9be027b71ac..624e321fb2b2 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.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. @@ -28,12 +28,12 @@ import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.ide.ui.LafManagerListener; import com.intellij.openapi.actionSystem.DataProvider; +import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.BaseComponent; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.extensions.AreaInstance; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.util.InvalidDataException; -import com.intellij.openapi.util.JDOMExternalizable; import com.intellij.openapi.util.WriteExternalException; import com.intellij.pom.Navigatable; import com.intellij.uiDesigner.core.GridConstraints; @@ -42,8 +42,6 @@ import com.intellij.util.PathUtil; import com.intellij.util.net.NetUtils; import com.intellij.xml.util.XmlStringUtil; import com.jgoodies.forms.layout.FormLayout; -import gnu.trove.THashMap; -import org.jdom.Document; import org.jdom.Element; import org.jetbrains.annotations.NotNull; @@ -86,15 +84,13 @@ public class SnapShooterConfigurationExtension extends RunConfigurationExtension paths.add(PathUtil.getJarPathForClass(ProjectComponent.class)); // openapi paths.add(PathUtil.getJarPathForClass(LwComponent.class)); // UIDesignerCore paths.add(PathUtil.getJarPathForClass(GridConstraints.class)); // forms_rt - paths.add(PathUtil.getJarPathForClass(JDOMExternalizable.class)); // util - paths.add(PathUtil.getJarPathForClass(Document.class)); // JDOM paths.add(PathUtil.getJarPathForClass(LafManagerListener.class)); // ui-impl paths.add(PathUtil.getJarPathForClass(DataProvider.class)); // action-system-openapi paths.add(PathUtil.getJarPathForClass(XmlStringUtil.class)); // idea paths.add(PathUtil.getJarPathForClass(Navigatable.class)); // pom paths.add(PathUtil.getJarPathForClass(AreaInstance.class)); // extensions - paths.add(PathUtil.getJarPathForClass(THashMap.class)); // trove4j paths.add(PathUtil.getJarPathForClass(FormLayout.class)); // jgoodies + paths.addAll(PathManager.getUtilClassPath()); for(String path: paths) { params.getClassPath().addFirst(path); } diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/PropertyEditor.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/PropertyEditor.java index 905b3fc515bc..c0892ab4cff2 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/PropertyEditor.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/PropertyEditor.java @@ -48,13 +48,13 @@ public abstract class PropertyEditor { myListenerList.remove(PropertyEditorListener.class, listener); } - protected final void fireEditingCancelled() { + public final void fireEditingCancelled() { for (PropertyEditorListener listener : myListenerList.getListeners(PropertyEditorListener.class)) { listener.editingCanceled(this); } } - protected final void fireValueCommitted(boolean continueEditing, boolean closeEditorOnError) { + public final void fireValueCommitted(boolean continueEditing, boolean closeEditorOnError) { for (PropertyEditorListener listener : myListenerList.getListeners(PropertyEditorListener.class)) { listener.valueCommitted(this, continueEditing, closeEditorOnError); } diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/editors/BooleanEditor.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/editors/BooleanEditor.java index d4ac1d7c9bbb..bc57cc10b9da 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/editors/BooleanEditor.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/editors/BooleanEditor.java @@ -52,16 +52,12 @@ public class BooleanEditor extends PropertyEditor { return Boolean.valueOf(myCheckBox.isSelected()); } - protected boolean getValue(Object value) { - return value != null && (Boolean)value; - } - @NotNull public JComponent getComponent(@NotNull RadComponent rootComponent, @Nullable RadComponent component, Object value) { try { myInsideChange = true; myCheckBox.setBackground(UIUtil.getTableBackground()); - myCheckBox.setSelected(getValue(value)); + myCheckBox.setSelected(value != null && (Boolean)value); return myCheckBox; } finally { diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/editors/ComboEditor.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/editors/ComboEditor.java index c851b8878561..dc661ab879fd 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/editors/ComboEditor.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/editors/ComboEditor.java @@ -15,12 +15,8 @@ */ package com.intellij.designer.propertyTable.editors; -import com.intellij.designer.model.RadComponent; import com.intellij.designer.propertyTable.PropertyEditor; import com.intellij.openapi.ui.ComboBox; -import com.intellij.openapi.ui.DialogWrapper; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.PopupMenuEvent; @@ -34,36 +30,17 @@ import java.awt.event.KeyEvent; */ public abstract class ComboEditor extends PropertyEditor { protected final ComboBox myCombo; - private boolean myCancelled; public ComboEditor() { myCombo = new ComboBox(-1); myCombo.setBorder(null); - myCombo.addPopupMenuListener(new PopupMenuListener() { + addEditorSupport(this, myCombo); + } - @Override - public void popupMenuWillBecomeVisible(PopupMenuEvent e) { - myCancelled = false; - } - - @Override - public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { - if (!myCancelled) { - fireValueCommitted(true, true); - } - } - - @Override - public void popupMenuCanceled(PopupMenuEvent e) { - myCancelled = true; - } - }); - myCombo.registerKeyboardAction(new ActionListener() { - public void actionPerformed(final ActionEvent e) { - myCancelled = true; - fireEditingCancelled(); - } - }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + public static void addEditorSupport(PropertyEditor editor, JComboBox myCombo) { + ComboListeners listeners = new ComboListeners(editor); + myCombo.addPopupMenuListener(listeners); + myCombo.registerKeyboardAction(listeners, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } @Override @@ -74,4 +51,36 @@ public abstract class ComboEditor extends PropertyEditor { SwingUtilities.updateComponentTreeUI((JComponent)renderer); } } + + private static class ComboListeners implements PopupMenuListener, ActionListener { + private final PropertyEditor myEditor; + private boolean myCancelled; + + public ComboListeners(PropertyEditor editor) { + myEditor = editor; + } + + @Override + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + myCancelled = false; + } + + @Override + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + if (!myCancelled) { + myEditor.fireValueCommitted(true, true); + } + } + + @Override + public void popupMenuCanceled(PopupMenuEvent e) { + myCancelled = true; + } + + @Override + public void actionPerformed(ActionEvent e) { + myCancelled = true; + myEditor.fireEditingCancelled(); + } + } } \ No newline at end of file diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/renderers/BooleanRenderer.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/renderers/BooleanRenderer.java index c3b8f1b72110..87f0ef2da5c0 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/renderers/BooleanRenderer.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/renderers/BooleanRenderer.java @@ -28,10 +28,6 @@ import javax.swing.*; * @author Vladimir Kondratyev */ public class BooleanRenderer extends JCheckBox implements PropertyRenderer { - protected boolean getValue(Object value) { - return value != null && (Boolean)value; - } - @NotNull public JComponent getComponent(@Nullable RadComponent component, @Nullable Object value, boolean selected, boolean hasFocus) { if (selected) { @@ -43,7 +39,7 @@ public class BooleanRenderer extends JCheckBox implements PropertyRenderer { setBackground(UIUtil.getTableBackground()); } - setSelected(getValue(value)); + setSelected(value != null && (Boolean)value); return this; } } \ No newline at end of file diff --git a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/renderers/LabelPropertyRenderer.java b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/renderers/LabelPropertyRenderer.java index 9af5f66d9c34..ac1117365212 100644 --- a/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/renderers/LabelPropertyRenderer.java +++ b/plugins/ui-designer/ui-designer-new/src/com/intellij/designer/propertyTable/renderers/LabelPropertyRenderer.java @@ -40,7 +40,8 @@ public class LabelPropertyRenderer extends JLabel implements PropertyRenderer { setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0)); } - public JLabel getComponent(@Nullable RadComponent component, @Nullable Object value, boolean selected, boolean hasFocus) { + @NotNull + public JComponent getComponent(@Nullable RadComponent component, @Nullable Object value, boolean selected, boolean hasFocus) { // Reset text and icon setText(null); setIcon(null); diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlUnusedNamespaceInspection.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlUnusedNamespaceInspection.java index ca59bb366f21..352e2176e382 100644 --- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlUnusedNamespaceInspection.java +++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlUnusedNamespaceInspection.java @@ -324,9 +324,11 @@ public class XmlUnusedNamespaceInspection extends XmlSuppressableInspectionTool public static void removeReferenceText(PsiReference ref) { PsiElement element = ref.getElement(); PsiFile file = element.getContainingFile(); - Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file); TextRange range = ref.getRangeInElement().shiftRight(element.getTextRange().getStartOffset()); + PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject()); + Document document = manager.getDocument(file); assert document != null; + manager.doPostponedOperationsAndUnblockDocument(document); document.deleteString(range.getStartOffset(), range.getEndOffset()); } diff --git a/xml/impl/src/com/intellij/xml/breadcrumbs/BreadcrumbsXmlWrapper.java b/xml/impl/src/com/intellij/xml/breadcrumbs/BreadcrumbsXmlWrapper.java index 3ad12afb0d29..d1b16c25325c 100644 --- a/xml/impl/src/com/intellij/xml/breadcrumbs/BreadcrumbsXmlWrapper.java +++ b/xml/impl/src/com/intellij/xml/breadcrumbs/BreadcrumbsXmlWrapper.java @@ -116,7 +116,7 @@ public class BreadcrumbsXmlWrapper implements BreadcrumbsItemListener