Merge commit 'origin/master'

This commit is contained in:
Maxim.Mossienko
2011-03-30 17:03:18 +04:00
100 changed files with 1202 additions and 689 deletions
Binary file not shown.
Binary file not shown.
+9 -9
View File
@@ -62,18 +62,17 @@ binding.setVariable("checkLibLicenses", {
}
if (!withoutLicenses.isEmpty()) {
project.warning("Licenses aren't specified for ${withoutLicenses.size()} libraries:")
def errorMessage = []
errorMessage << "Licenses aren't specified for ${withoutLicenses.size()} libraries:"
withoutLicenses.sort(String.CASE_INSENSITIVE_ORDER)
withoutLicenses.each { project.warning(it); }
withoutLicenses.each { errorMessage << it}
errorMessage << "If a library is packaged into IDEA installation information about its license must be added to libLicenses.gant file"
errorMessage << "If a library is used in tests only change its scope to 'Test'"
errorMessage << "If a library is used for compilation only change its scope to 'Provided'"
project.error(errorMessage.join("\n"))
}
});
binding.setVariable("checkLibLicensesAndGenerateTable", {String filePath, Set<String> usedModules ->
checkLibLicenses();
generateLicensesTable(filePath, usedModules)
notifyArtifactBuilt(filePath)
})
binding.setVariable("generateLicensesTable", {String filePath, Set<String> usedModulesNames ->
project.info("Generating licenses table")
project.info("Used modules: $usedModulesNames")
@@ -110,7 +109,7 @@ binding.setVariable("generateLicensesTable", {String filePath, Set<String> usedM
def name = lib.url != null ? "[$lib.name|$lib.url]" : lib.name
def license = lib.licenseUrl != null ? "[$lib.license|$lib.licenseUrl]" : lib.license
project.info(" $lib.name (in module $moduleName)")
lines << "|$name| $lib.version|$license|".toString()
lines << "|$name| ${lib.version?:""}|$license|".toString()
}
//project.info("Unused libraries:")
//licensesList.findAll {!licenses.containsKey(it)}.each {LibraryLicense lib ->
@@ -130,6 +129,7 @@ binding.setVariable("generateLicensesTable", {String filePath, Set<String> usedM
finally {
out.close()
}
notifyArtifactBuilt(filePath)
})
libraryLicense(name: "Alloy L&F", libraryName: "alloy.jar", version: "1.4.4", license: "link (company license)", url: "http://www.incors.com/lookandfeel/", licenseUrl: "http://lookandfeel.incors.com/display_licence.php?back=purchase.php&selMenu=Purchase")
@@ -57,7 +57,7 @@ public class MemberLookupHelper {
final String qname = myContainingClass == null ? "" : myContainingClass.getQualifiedName();
String pkg = qname == null ? "" : StringUtil.getPackageName(qname);
String location = StringUtil.isEmpty(pkg) ? "" : " (" + pkg + ")";
String location = Boolean.FALSE.equals(qualify) || StringUtil.isEmpty(pkg) ? "" : " (" + pkg + ")";
final String params = myMergedOverloads
? "(...)"
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2011 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.
@@ -13,20 +13,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders;
package com.intellij.refactoring.move.moveInner;
import com.intellij.lang.surroundWith.Surrounder;
import com.intellij.psi.PsiElement;
import com.intellij.lang.LanguageExtension;
import com.intellij.psi.PsiClass;
import org.jetbrains.annotations.NotNull;
/**
* User: Dmitry.Krasilschikov
* Date: 22.05.2007
*/
abstract public class GroovySingleElementSurrounder implements Surrounder {
public boolean isApplicable(@NotNull PsiElement[] elements) {
return elements.length == 1 && isApplicable(elements[0]);
}
public interface MoveInnerHandler {
LanguageExtension<MoveInnerHandler> EP_NAME = new LanguageExtension<MoveInnerHandler>("com.intellij.refactoring.moveInnerHandler");
protected abstract boolean isApplicable(PsiElement element);
}
@NotNull
PsiClass copyClass(@NotNull MoveInnerOptions options);
}
@@ -0,0 +1,52 @@
/*
* Copyright 2000-2011 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.move.moveInner;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
public class MoveInnerOptions {
private final PsiClass myInnerClass;
private final PsiClass myOuterClass;
private final PsiElement myTargetContainer;
private final String myNewClassName;
public MoveInnerOptions(final PsiClass innerClass,
final PsiClass outerClass,
final PsiElement targetContainer,
final String newClassName) {
myInnerClass = innerClass;
myOuterClass = outerClass;
myTargetContainer = targetContainer;
myNewClassName = newClassName;
}
public PsiClass getInnerClass() {
return myInnerClass;
}
public PsiClass getOuterClass() {
return myOuterClass;
}
public PsiElement getTargetContainer() {
return myTargetContainer;
}
public String getNewClassName() {
return myNewClassName;
}
}
@@ -13,12 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* created at Sep 24, 2001
* @author Jeka
*/
package com.intellij.refactoring.move.moveInner;
import com.intellij.codeInsight.ChangeContextUtil;
@@ -32,11 +26,9 @@ import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.listeners.RefactoringElementListener;
@@ -63,6 +55,10 @@ import java.util.Collection;
import java.util.HashSet;
import java.util.List;
/**
* created at Sep 24, 2001
* @author Jeka
*/
public class MoveInnerProcessor extends BaseRefactoringProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.move.moveInner.MoveInnerProcessor");
@@ -98,6 +94,7 @@ public class MoveInnerProcessor extends BaseRefactoringProcessor {
return RefactoringBundle.message("move.inner.class.command", myDescriptiveName);
}
@NotNull
protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) {
return new MoveInnerViewDescriptor(myInnerClass);
}
@@ -161,13 +158,11 @@ public class MoveInnerProcessor extends BaseRefactoringProcessor {
mySearchInNonJavaFiles = searchInNonJavaFiles;
}
protected void performRefactoring(final UsageInfo[] usages) {
PsiManager manager = PsiManager.getInstance(myProject);
final PsiManager manager = PsiManager.getInstance(myProject);
final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
final RefactoringElementListener elementListener = getTransaction().getElementListener(myInnerClass);
String newClassName = myNewClassName;
try {
PsiField field = null;
if (myParameterNameOuterClass != null) {
@@ -180,39 +175,11 @@ public class MoveInnerProcessor extends BaseRefactoringProcessor {
ChangeContextUtil.encodeContextInfo(myInnerClass, false);
PsiClass newClass;
if (myTargetContainer instanceof PsiDirectory) {
myInnerClass = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(myInnerClass);
newClass = JavaDirectoryService.getInstance().createClass((PsiDirectory)myTargetContainer, newClassName);
PsiDocComment defaultDocComment = newClass.getDocComment();
if (defaultDocComment != null && myInnerClass.getDocComment() == null) {
myInnerClass = (PsiClass)myInnerClass.addAfter(defaultDocComment, null).getParent();
}
myInnerClass = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(myInnerClass);
newClass = (PsiClass)newClass.replace(myInnerClass);
PsiUtil.setModifierProperty(newClass, PsiModifier.STATIC, false);
PsiUtil.setModifierProperty(newClass, PsiModifier.PRIVATE, false);
PsiUtil.setModifierProperty(newClass, PsiModifier.PROTECTED, false);
final boolean makePublic = needPublicAccess();
if (makePublic) {
PsiUtil.setModifierProperty(newClass, PsiModifier.PUBLIC, true);
}
final PsiMethod[] constructors = newClass.getConstructors();
for (PsiMethod constructor : constructors) {
final PsiModifierList modifierList = constructor.getModifierList();
modifierList.setModifierProperty(PsiModifier.PRIVATE, false);
modifierList.setModifierProperty(PsiModifier.PROTECTED, false);
if (makePublic) {
modifierList.setModifierProperty(PsiModifier.PUBLIC, true);
}
}
}
else {
newClass = (PsiClass)myTargetContainer.add(myInnerClass);
}
newClass.setName(newClassName);
final MoveInnerOptions moveInnerOptions = new MoveInnerOptions(myInnerClass, myOuterClass, myTargetContainer, myNewClassName);
final MoveInnerHandler handler = MoveInnerHandler.EP_NAME.forLanguage(myInnerClass.getLanguage());
final PsiClass newClass = handler.copyClass(moveInnerOptions);
// replace references in a new class to old inner class with references to itself
for (PsiReference ref : ReferencesSearch.search(myInnerClass, new LocalSearchScope(newClass), true)) {
@@ -326,19 +293,6 @@ public class MoveInnerProcessor extends BaseRefactoringProcessor {
}
}
private boolean needPublicAccess() {
if (myOuterClass.isInterface()) {
return true;
}
if (myTargetContainer instanceof PsiDirectory) {
PsiPackage targetPackage = JavaDirectoryService.getInstance().getPackage((PsiDirectory)myTargetContainer);
if (targetPackage != null && !isInPackage(myOuterClass.getContainingFile(), targetPackage)) {
return true;
}
}
return false;
}
protected void performPsiSpoilingRefactoring() {
if (myNonCodeUsages != null) {
RenameUtil.renameNonCodeUsages(myProject, myNonCodeUsages);
@@ -411,10 +365,11 @@ public class MoveInnerProcessor extends BaseRefactoringProcessor {
final String visibilityModifier = VisibilityUtil.getVisibilityModifier(element.getModifierList());
if (PsiModifier.PRIVATE.equals(visibilityModifier)) return true;
if (PsiModifier.PUBLIC.equals(visibilityModifier)) return false;
final PsiFile containingFile = myOuterClass.getContainingFile();
final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(myProject);
if (myTargetContainer instanceof PsiDirectory) {
final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage((PsiDirectory)myTargetContainer);
return !isInPackage(containingFile, aPackage);
assert aPackage != null : myTargetContainer;
return !psiFacade.isInPackage(myOuterClass, aPackage);
}
// target container is a class
PsiFile targetFile = myTargetContainer.getContainingFile();
@@ -422,26 +377,13 @@ public class MoveInnerProcessor extends BaseRefactoringProcessor {
final PsiDirectory containingDirectory = targetFile.getContainingDirectory();
if (containingDirectory != null) {
final PsiPackage targetPackage = JavaDirectoryService.getInstance().getPackage(containingDirectory);
return isInPackage(containingFile, targetPackage);
assert targetPackage != null : myTargetContainer;
return psiFacade.isInPackage(myOuterClass, targetPackage);
}
}
return false;
}
private static boolean isInPackage(final PsiFile containingFile, PsiPackage aPackage) {
if (containingFile != null) {
final PsiDirectory containingDirectory = containingFile.getContainingDirectory();
if (containingDirectory != null) {
PsiPackage filePackage = JavaDirectoryService.getInstance().getPackage(containingDirectory);
if (filePackage != null && !filePackage.getQualifiedName().equals(
aPackage.getQualifiedName())) {
return false;
}
}
}
return true;
}
public void setup(final PsiClass innerClass,
final String className,
final boolean passOuterClass,
@@ -507,12 +449,12 @@ public class MoveInnerProcessor extends BaseRefactoringProcessor {
}
}
private PsiStatement createAssignmentStatement(PsiMethod constructor, String fieldname, String parameterName)
private PsiStatement createAssignmentStatement(PsiMethod constructor, String fieldName, String parameterName)
throws IncorrectOperationException {
PsiElementFactory factory = JavaPsiFacade.getInstance(myProject).getElementFactory();
@NonNls String pattern = fieldname + "=a;";
if (fieldname.equals(parameterName)) {
@NonNls String pattern = fieldName + "=a;";
if (fieldName.equals(parameterName)) {
pattern = "this." + pattern;
}
@@ -520,11 +462,14 @@ public class MoveInnerProcessor extends BaseRefactoringProcessor {
statement = (PsiExpressionStatement)CodeStyleManager.getInstance(myProject).reformat(statement);
PsiCodeBlock body = constructor.getBody();
assert body != null : constructor;
statement = (PsiExpressionStatement)body.addAfter(statement, getAnchorElement(body));
PsiAssignmentExpression assignment = (PsiAssignmentExpression)statement.getExpression();
PsiReferenceExpression rExpr = (PsiReferenceExpression)assignment.getRExpression();
assert rExpr != null : assignment;
PsiIdentifier identifier = (PsiIdentifier)rExpr.getReferenceNameElement();
assert identifier != null : assignment;
identifier.replace(factory.createIdentifier(parameterName));
return statement;
}
@@ -0,0 +1,78 @@
/*
* Copyright 2000-2011 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.move.moveInner;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
public class MoveJavaInnerHandler implements MoveInnerHandler {
@NotNull
@Override
public PsiClass copyClass(@NotNull final MoveInnerOptions options) {
PsiClass innerClass = options.getInnerClass();
PsiClass newClass;
if (options.getTargetContainer() instanceof PsiDirectory) {
newClass = JavaDirectoryService.getInstance().createClass((PsiDirectory)options.getTargetContainer(), options.getNewClassName());
PsiDocComment defaultDocComment = newClass.getDocComment();
if (defaultDocComment != null && innerClass.getDocComment() == null) {
innerClass = (PsiClass)innerClass.addAfter(defaultDocComment, null).getParent();
}
newClass = (PsiClass)newClass.replace(innerClass);
PsiUtil.setModifierProperty(newClass, PsiModifier.STATIC, false);
PsiUtil.setModifierProperty(newClass, PsiModifier.PRIVATE, false);
PsiUtil.setModifierProperty(newClass, PsiModifier.PROTECTED, false);
final boolean makePublic = needPublicAccess(options.getOuterClass(), options.getTargetContainer());
if (makePublic) {
PsiUtil.setModifierProperty(newClass, PsiModifier.PUBLIC, true);
}
final PsiMethod[] constructors = newClass.getConstructors();
for (PsiMethod constructor : constructors) {
final PsiModifierList modifierList = constructor.getModifierList();
modifierList.setModifierProperty(PsiModifier.PRIVATE, false);
modifierList.setModifierProperty(PsiModifier.PROTECTED, false);
if (makePublic) {
modifierList.setModifierProperty(PsiModifier.PUBLIC, true);
}
}
}
else {
newClass = (PsiClass)options.getTargetContainer().add(innerClass);
}
newClass.setName(options.getNewClassName());
return newClass;
}
protected static boolean needPublicAccess(final PsiClass outerClass, final PsiElement targetContainer) {
if (outerClass.isInterface()) {
return true;
}
if (targetContainer instanceof PsiDirectory) {
final PsiPackage targetPackage = JavaDirectoryService.getInstance().getPackage((PsiDirectory)targetContainer);
final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(outerClass.getProject());
if (targetPackage != null && !psiFacade.isInPackage(outerClass, targetPackage)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,5 @@
class Foo {
{
"".equals<caret>
}
}
@@ -14,6 +14,7 @@ import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMethod
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.codeInsight.lookup.LookupElementPresentation
public class NormalCompletionTest extends LightFixtureCompletionTestCase {
@Override
@@ -116,6 +117,18 @@ public class NormalCompletionTest extends LightFixtureCompletionTestCase {
public void testSimpleVariable() throws Exception { doTest() }
public void testMethodItemPresentation() {
configure()
def presentation = new LookupElementPresentation()
myItems[0].renderElement(presentation)
assert "equals" == presentation.itemText
assert "(Object anObject)" == presentation.tailText
assert "boolean" == presentation.typeText
assert !presentation.tailGrayed
assert presentation.itemTextBold
}
public void testPreferLongerNamesOption() throws Exception {
configureByFile("PreferLongerNamesOption.java");
@@ -45,15 +45,19 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiPackage;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.search.ProjectScope;
import com.intellij.testFramework.PsiTestCase;
import com.intellij.testFramework.PsiTestData;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
@@ -681,4 +685,18 @@ public abstract class CodeInsightTestCase extends PsiTestCase {
event.setInjectedContext(true);
action.actionPerformed(event);
}
@NotNull
protected PsiClass findClass(@NotNull @NonNls final String name) {
final PsiClass aClass = myJavaFacade.findClass(name, ProjectScope.getProjectScope(getProject()));
assertNotNull("Class " + name + " not found", aClass);
return aClass;
}
@NotNull
protected PsiPackage findPackage(@NotNull @NonNls final String name) {
final PsiPackage aPackage = myJavaFacade.findPackage(name);
assertNotNull("Package " + name + " not found", aPackage);
return aPackage;
}
}
@@ -21,7 +21,6 @@ import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.psi.PsiClass;
import com.intellij.psi.impl.JavaPsiFacadeEx;
import org.jetbrains.annotations.NonNls;
import java.util.Arrays;
import java.util.Comparator;
@@ -29,14 +28,28 @@ import java.util.Comparator;
/**
* @author mike
*/
@NonNls public abstract class IdeaTestCase extends PlatformTestCase {
public abstract class IdeaTestCase extends PlatformTestCase {
protected JavaPsiFacadeEx myJavaFacade;
@Override
protected void setUp() throws Exception {
super.setUp();
myJavaFacade = JavaPsiFacadeEx.getInstanceEx(myProject);
}
@Override
protected void tearDown() throws Exception {
myJavaFacade = null;
super.tearDown();
}
@SuppressWarnings({"JUnitTestCaseWithNonTrivialConstructors"})
protected IdeaTestCase() {
initPlatformPrefix();
}
public final JavaPsiFacadeEx getJavaFacade() {
return JavaPsiFacadeEx.getInstanceEx(myProject);
return myJavaFacade;
}
@Override
@@ -32,7 +32,6 @@ import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.JavaPsiFacadeImpl;
import com.intellij.psi.impl.PsiManagerImpl;
import com.intellij.util.IncorrectOperationException;
import org.jdom.Document;
@@ -49,8 +48,6 @@ import java.util.StringTokenizer;
*/
public abstract class PsiTestCase extends ModuleTestCase {
protected PsiManagerImpl myPsiManager;
protected JavaPsiFacadeImpl myJavaFacade;
protected PsiFile myFile;
protected PsiTestData myTestDataBefore;
protected PsiTestData myTestDataAfter;
@@ -60,12 +57,10 @@ public abstract class PsiTestCase extends ModuleTestCase {
protected void setUp() throws Exception {
super.setUp();
myPsiManager = (PsiManagerImpl) PsiManager.getInstance(myProject);
myJavaFacade = (JavaPsiFacadeImpl) JavaPsiFacade.getInstance(myProject);
}
@Override
protected void tearDown() throws Exception {
myJavaFacade = null;
myPsiManager = null;
myFile = null;
myTestDataBefore = null;
@@ -15,7 +15,6 @@
*/
package com.intellij.navigation;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
@@ -30,5 +29,5 @@ public abstract class GotoRelatedProvider {
public static final ExtensionPointName<GotoRelatedProvider> EP_NAME = ExtensionPointName.create("com.intellij.gotoRelatedProvider");
@NotNull
public abstract List<GotoRelatedItem> getItems(PsiElement context);
public abstract List<? extends GotoRelatedItem> getItems(@NotNull PsiElement context);
}
@@ -18,6 +18,7 @@ package com.intellij.navigation;
import com.intellij.psi.NavigatablePsiElement;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
@@ -52,4 +53,9 @@ public class PsiGotoRelatedItem extends GotoRelatedItem {
public PsiFile getContainingFile() {
return myElement instanceof PsiFile ? null : myElement.getContainingFile();
}
@TestOnly
public NavigatablePsiElement getElement() {
return myElement;
}
}
@@ -1,15 +1,13 @@
package com.intellij.psi;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
/**
* @author traff
*/
public class PsiReferenceWrapper implements PsiReference{
public class PsiReferenceWrapper implements PsiReference {
private final PsiReference myOriginalPsiReference;
public PsiReferenceWrapper(PsiReference originalPsiReference) {
@@ -62,4 +60,18 @@ public class PsiReferenceWrapper implements PsiReference{
public boolean isSoft() {
return myOriginalPsiReference.isSoft();
}
public <T extends PsiReference> boolean isInstance(Class<T> clazz) {
if (myOriginalPsiReference instanceof PsiReferenceWrapper) {
return ((PsiReferenceWrapper)myOriginalPsiReference).isInstance(clazz);
}
return clazz.isInstance(myOriginalPsiReference);
}
public <T extends PsiReference> T cast(Class<T> clazz) {
if (myOriginalPsiReference instanceof PsiReferenceWrapper) {
return ((PsiReferenceWrapper)myOriginalPsiReference).cast(clazz);
}
return clazz.cast(myOriginalPsiReference);
}
}
@@ -43,6 +43,7 @@ public class CodeStyleMainPanel extends JPanel implements LanguageSelectorListen
private final CodeStyleSettingsPanelFactory myFactory;
private final CodeStyleSchemesPanel mySchemesPanel;
private final LanguageSelector myLangSelector;
private boolean myIsDisposed = false;
@NonNls
private static final String WAIT_CARD = "CodeStyleSchemesConfigurable.$$$.Wait.placeholder.$$$";
@@ -113,8 +114,10 @@ public class CodeStyleMainPanel extends JPanel implements LanguageSelectorListen
myLayout.show(mySettingsPanel, WAIT_CARD);
final Runnable replaceLayout = new Runnable() {
public void run() {
ensureCurrentPanel().onSomethingChanged();
myLayout.show(mySettingsPanel, myModel.getSelectedScheme().getName());
if (!myIsDisposed) {
ensureCurrentPanel().onSomethingChanged();
myLayout.show(mySettingsPanel, myModel.getSelectedScheme().getName());
}
}
};
if (ApplicationManager.getApplication().isHeadlessEnvironment()) {
@@ -206,6 +209,7 @@ public class CodeStyleMainPanel extends JPanel implements LanguageSelectorListen
myAlarm.cancelAllRequests();
clearPanels();
myLangSelector.removeListener(this);
myIsDisposed = true;
}
public boolean isModified(final CodeStyleScheme scheme) {
@@ -42,6 +42,7 @@ public abstract class BaseCodeCompletionAction extends AnAction implements HintM
protected BaseCodeCompletionAction(CompletionType completionType) {
myCompletionType = completionType;
setEnabledInModalContext(true);
setInjectedContext(true);
}
public void actionPerformed(AnActionEvent e) {
@@ -1,155 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.generation.surroundWith;
import com.intellij.codeInsight.template.CustomLiveTemplate;
import com.intellij.codeInsight.template.impl.InvokeTemplateAction;
import com.intellij.codeInsight.template.impl.SurroundWithTemplateHandler;
import com.intellij.codeInsight.template.impl.TemplateImpl;
import com.intellij.codeInsight.template.impl.WrapWithCustomTemplateAction;
import com.intellij.ide.DataManager;
import com.intellij.lang.surroundWith.Surrounder;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.ui.UIUtil;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PopupActionChooser {
private final String myTitle;
private boolean hasEnabledSurrounders;
public PopupActionChooser(String title) {
myTitle = title;
}
public void invoke(final Project project, final Editor editor, final PsiFile file, final Surrounder[] surrounders, final PsiElement[] elements){
final DefaultActionGroup applicable = new DefaultActionGroup();
hasEnabledSurrounders = false;
Set<Character> usedMnemonicsSet = new HashSet<Character>();
int index = 0;
for (Surrounder surrounder : surrounders) {
if (surrounder.isApplicable(elements)) {
char mnemonic;
if (index < 9) {
mnemonic = (char)('0' + index + 1);
}
else if (index == 9) {
mnemonic = '0';
}
else {
mnemonic = (char)('A' + index - 10);
}
index++;
usedMnemonicsSet.add(Character.toUpperCase(mnemonic));
applicable.add(new InvokeSurrounderAction(surrounder, project, editor, elements, mnemonic));
hasEnabledSurrounders = true;
}
}
List<CustomLiveTemplate> customTemplates = SurroundWithTemplateHandler.getApplicableCustomTemplates(editor, file);
List<TemplateImpl> templates = SurroundWithTemplateHandler.getApplicableTemplates(editor, file, true);
if (!templates.isEmpty() || !customTemplates.isEmpty()) {
applicable.addSeparator("Live templates");
}
for (TemplateImpl template : templates) {
applicable.add(new InvokeTemplateAction(template, editor, project, usedMnemonicsSet));
hasEnabledSurrounders = true;
}
for (CustomLiveTemplate customTemplate : customTemplates) {
applicable.add(new WrapWithCustomTemplateAction(customTemplate, editor, file, usedMnemonicsSet));
hasEnabledSurrounders = true;
}
if (!templates.isEmpty() || !customTemplates.isEmpty()) {
applicable.addSeparator();
applicable.add(new ConfigureTemplatesAction());
}
if (hasEnabledSurrounders) {
DataContext context = DataManager.getInstance().getDataContext(editor.getContentComponent());
final ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup(myTitle,
applicable,
context,
JBPopupFactory.ActionSelectionAid.MNEMONICS,
true);
popup.showInBestPositionFor(editor);
}
}
private static class InvokeSurrounderAction extends AnAction {
private final Surrounder mySurrounder;
private final Project myProject;
private final Editor myEditor;
private final PsiElement[] myElements;
public InvokeSurrounderAction(Surrounder surrounder, Project project, Editor editor, PsiElement[] elements, char mnemonic) {
super(UIUtil.MNEMONIC + String.valueOf(mnemonic) + ". " + surrounder.getTemplateDescription());
mySurrounder = surrounder;
myProject = project;
myEditor = editor;
myElements = elements;
}
public void actionPerformed(AnActionEvent e) {
CommandProcessor.getInstance().executeCommand(
myProject, new Runnable(){
public void run(){
final Runnable action = new Runnable(){
public void run(){
SurroundWithHandler.doSurround(myProject, myEditor, mySurrounder, myElements);
}
};
ApplicationManager.getApplication().runWriteAction(action);
}
},
null,
null
);
}
}
public boolean isHasEnabledSurrounders() {
return hasEnabledSurrounders;
}
private static class ConfigureTemplatesAction extends AnAction {
private ConfigureTemplatesAction() {
super("Configure Live Templates...");
}
public void actionPerformed(AnActionEvent e) {
ShowSettingsUtil.getInstance().showSettingsDialog(e.getData(PlatformDataKeys.PROJECT), "Live Templates");
}
}
}
@@ -18,27 +18,43 @@ package com.intellij.codeInsight.generation.surroundWith;
import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.template.CustomLiveTemplate;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.codeInsight.template.impl.InvokeTemplateAction;
import com.intellij.codeInsight.template.impl.SurroundWithTemplateHandler;
import com.intellij.codeInsight.template.impl.TemplateImpl;
import com.intellij.codeInsight.template.impl.WrapWithCustomTemplateAction;
import com.intellij.ide.DataManager;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageSurrounders;
import com.intellij.lang.surroundWith.SurroundDescriptor;
import com.intellij.lang.surroundWith.Surrounder;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SurroundWithHandler implements CodeInsightActionHandler{
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.surroundWith.SurroundWithHandler");
@@ -49,10 +65,18 @@ public class SurroundWithHandler implements CodeInsightActionHandler{
}
public boolean startInWriteAction() {
return true;
return false;
}
public static void invoke(final Project project, final Editor editor, PsiFile file, Surrounder surrounder){
List<AnAction> applicable = buildSurroundActions(project, editor, file, surrounder);
if (applicable != null) {
showPopup(editor, applicable);
}
}
@Nullable
public static List<AnAction> buildSurroundActions(final Project project, final Editor editor, PsiFile file, @Nullable Surrounder surrounder){
if (!editor.getSelectionModel().hasSelection()) {
editor.getSelectionModel().selectLineAtCaret();
}
@@ -64,12 +88,12 @@ public class SurroundWithHandler implements CodeInsightActionHandler{
PsiElement element1 = file.findElementAt(startOffset);
PsiElement element2 = file.findElementAt(endOffset - 1);
if (element1 == null || element2 == null) return;
if (element1 == null || element2 == null) return null;
TextRange textRange = new TextRange(startOffset, endOffset);
for(SurroundWithRangeAdjuster adjuster: Extensions.getExtensions(SurroundWithRangeAdjuster.EP_NAME)) {
textRange = adjuster.adjustSurroundWithRange(file, textRange);
if (textRange == null) return;
if (textRange == null) return null;
}
startOffset = textRange.getStartOffset();
endOffset = textRange.getEndOffset();
@@ -82,29 +106,48 @@ public class SurroundWithHandler implements CodeInsightActionHandler{
surroundDescriptors.addAll(LanguageSurrounders.INSTANCE.allForLanguage(l));
if (l != baseLanguage) surroundDescriptors.addAll(LanguageSurrounders.INSTANCE.allForLanguage(baseLanguage));
if (surrounder != null) {
invokeSurrounderInTests(project, editor, file, surrounder, startOffset, endOffset, surroundDescriptors);
return null;
}
for (SurroundDescriptor descriptor : surroundDescriptors) {
final PsiElement[] elements = descriptor.getElementsToSurround(file, startOffset, endOffset);
if (elements.length > 0) {
if (surrounder == null) { //production
PopupActionChooser popupActionChooser = new PopupActionChooser(CHOOSER_TITLE);
popupActionChooser.invoke(project, editor, file, descriptor.getSurrounders(), elements);
if (popupActionChooser.isHasEnabledSurrounders()) return;
}
else {
doSurround(project, editor, surrounder, elements);
return;
List<AnAction> applicable = buildSurroundActions(project, editor, file, descriptor.getSurrounders(), elements);
if (applicable != null) {
return applicable;
}
}
}
if (surrounder == null) { //if only templates are available
PopupActionChooser popupActionChooser = new PopupActionChooser(CHOOSER_TITLE);
popupActionChooser.invoke(project, editor, file, new Surrounder[0], new PsiElement[0]);
return buildSurroundActions(project, editor, file, new Surrounder[0], new PsiElement[0]);
}
private static void invokeSurrounderInTests(Project project,
Editor editor,
PsiFile file,
Surrounder surrounder,
int startOffset,
int endOffset, List<SurroundDescriptor> surroundDescriptors) {
assert ApplicationManager.getApplication().isUnitTestMode();
for (SurroundDescriptor descriptor : surroundDescriptors) {
final PsiElement[] elements = descriptor.getElementsToSurround(file, startOffset, endOffset);
if (elements.length > 0) {
doSurround(project, editor, surrounder, elements);
return;
}
}
}
private static void showPopup(Editor editor, List<AnAction> applicable) {
DataContext context = DataManager.getInstance().getDataContext(editor.getContentComponent());
JBPopupFactory.ActionSelectionAid mnemonics = JBPopupFactory.ActionSelectionAid.MNEMONICS;
DefaultActionGroup group = new DefaultActionGroup(applicable.toArray(new AnAction[applicable.size()]));
JBPopupFactory.getInstance().createActionGroupPopup(CHOOSER_TITLE, group, context, mnemonics, true).showInBestPositionFor(editor);
}
static void doSurround(final Project project, final Editor editor, final Surrounder surrounder, final PsiElement[] elements) {
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)){
return;
}
@@ -131,4 +174,93 @@ public class SurroundWithHandler implements CodeInsightActionHandler{
LOG.error(e);
}
}
@Nullable
private static List<AnAction> buildSurroundActions(Project project,
Editor editor,
PsiFile file,
Surrounder[] surrounders,
PsiElement[] elements) {
final List<AnAction> applicable = new ArrayList<AnAction>();
boolean hasEnabledSurrounders = false;
Set<Character> usedMnemonicsSet = new HashSet<Character>();
int index = 0;
for (Surrounder surrounder : surrounders) {
if (surrounder.isApplicable(elements)) {
char mnemonic;
if (index < 9) {
mnemonic = (char)('0' + index + 1);
}
else if (index == 9) {
mnemonic = '0';
}
else {
mnemonic = (char)('A' + index - 10);
}
index++;
usedMnemonicsSet.add(Character.toUpperCase(mnemonic));
applicable.add(new InvokeSurrounderAction(surrounder, project, editor, elements, mnemonic));
hasEnabledSurrounders = true;
}
}
List<CustomLiveTemplate> customTemplates = SurroundWithTemplateHandler.getApplicableCustomTemplates(editor, file);
List<TemplateImpl> templates = SurroundWithTemplateHandler.getApplicableTemplates(editor, file, true);
if (!templates.isEmpty() || !customTemplates.isEmpty()) {
applicable.add(new Separator("Live templates"));
}
for (TemplateImpl template : templates) {
applicable.add(new InvokeTemplateAction(template, editor, project, usedMnemonicsSet));
hasEnabledSurrounders = true;
}
for (CustomLiveTemplate customTemplate : customTemplates) {
applicable.add(new WrapWithCustomTemplateAction(customTemplate, editor, file, usedMnemonicsSet));
hasEnabledSurrounders = true;
}
if (!templates.isEmpty() || !customTemplates.isEmpty()) {
applicable.add(Separator.getInstance());
applicable.add(new ConfigureTemplatesAction());
}
return hasEnabledSurrounders ? applicable : null;
}
private static class InvokeSurrounderAction extends AnAction {
private final Surrounder mySurrounder;
private final Project myProject;
private final Editor myEditor;
private final PsiElement[] myElements;
public InvokeSurrounderAction(Surrounder surrounder, Project project, Editor editor, PsiElement[] elements, char mnemonic) {
super(UIUtil.MNEMONIC + String.valueOf(mnemonic) + ". " + surrounder.getTemplateDescription());
mySurrounder = surrounder;
myProject = project;
myEditor = editor;
myElements = elements;
}
public void actionPerformed(AnActionEvent e) {
new WriteCommandAction(myProject) {
@Override
protected void run(Result result) throws Exception {
doSurround(myProject, myEditor, mySurrounder, myElements);
}
}.execute();
}
}
private static class ConfigureTemplatesAction extends AnAction {
private ConfigureTemplatesAction() {
super("Configure Live Templates...");
}
public void actionPerformed(AnActionEvent e) {
ShowSettingsUtil.getInstance().showSettingsDialog(e.getData(PlatformDataKeys.PROJECT), "Live Templates");
}
}
}
@@ -159,6 +159,7 @@ public class LanguageConsoleImpl implements Disposable, TypeSafeDataProvider {
myPanel.add(myConsoleEditor.getComponent());
myHistoryViewer.setHorizontalScrollbarVisible(false);
myCurrentEditor = myConsoleEditor;
}
else {
myPanel.removeAll();
@@ -168,6 +169,7 @@ public class LanguageConsoleImpl implements Disposable, TypeSafeDataProvider {
setConsoleFilePinned(fileManager);
myHistoryViewer.setHorizontalScrollbarVisible(true);
myCurrentEditor = myFullEditor;
}
}
@@ -515,14 +517,6 @@ public class LanguageConsoleImpl implements Disposable, TypeSafeDataProvider {
queueUiUpdate(false);
}
});
editor.getContentComponent().addFocusListener(new FocusListener() {
public void focusGained(final FocusEvent e) {
myCurrentEditor = editor;
}
public void focusLost(final FocusEvent e) {
}
});
}
}
}
@@ -74,7 +74,7 @@ import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;
public class ShowUsagesAction extends AnAction {
public class ShowUsagesAction extends AnAction implements PopupAction {
private final boolean showSettingsDialogBefore;
private static final int USAGES_PAGE_SIZE = 100;
@@ -75,7 +75,7 @@ public class ExternalJavaDocAction extends AnAction {
public static void showExternalJavadoc(List<String> urls) {
final HashSet<String> set = new HashSet<String>(urls);
if (set.size() > 1) {
JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<String>("Choose javadoc root", ArrayUtil.toStringArray(set)) {
JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<String>("Choose external documentation root", ArrayUtil.toStringArray(set)) {
public PopupStep onChosen(final String selectedValue, final boolean finalChoice) {
BrowserUtil.launchBrowser(selectedValue);
return FINAL_CHOICE;
@@ -26,6 +26,8 @@ import com.intellij.psi.PsiFile;
import com.intellij.ui.CollectionListModel;
import com.intellij.ui.components.JBList;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
@@ -45,7 +47,7 @@ public class GotoRelatedFileAction extends AnAction {
PsiFile psiFile = LangDataKeys.PSI_FILE.getData(context);
if (psiFile == null) return;
List<GotoRelatedItem> items = getItems(editor, psiFile);
List<GotoRelatedItem> items = getItems(psiFile, editor);
if (items.isEmpty()) return;
if (items.size() == 1) {
items.get(0).navigate();
@@ -71,17 +73,20 @@ public class GotoRelatedFileAction extends AnAction {
.showInBestPositionFor(context);
}
public static List<GotoRelatedItem> getItems(Editor editor, PsiFile psiFile) {
PsiElement psiElement = psiFile;
@NotNull
public static List<GotoRelatedItem> getItems(@NotNull PsiFile psiFile, @Nullable Editor editor) {
PsiElement context = psiFile;
if (editor != null) {
psiElement = psiFile.findElementAt(editor.getCaretModel().getOffset());
PsiElement element = psiFile.findElementAt(editor.getCaretModel().getOffset());
if (element != null) {
context = element;
}
}
List<GotoRelatedItem> items = new ArrayList<GotoRelatedItem>();
for (GotoRelatedProvider provider : Extensions.getExtensions(GotoRelatedProvider.EP_NAME)) {
items.addAll(provider.getItems(psiElement));
items.addAll(provider.getItems(context));
}
return items;
}
@@ -91,7 +91,7 @@ public class NavBarPopup extends LightweightHint {
});
} else {
show(myPanel, p.x, p.y, myPanel, new HintHint(myPanel, p));
getList().setSelectedIndex(myIndex);
ListScrollingUtil.selectItem(getList(), myIndex);
}
}
@@ -193,7 +193,7 @@ public class RegistryUi implements Disposable {
private final List<RegistryValue> myAll;
private MyTableModel() {
myAll = Registry.getInstance().getAll();
myAll = Registry.getAll();
Collections.sort(myAll, new Comparator<RegistryValue>() {
public int compare(RegistryValue o1, RegistryValue o2) {
return o1.getKey().compareTo(o2.getKey());
@@ -276,8 +276,17 @@ public class RegistryUi implements Disposable {
}
}};
}
};
@Override
public void doCancelAction() {
final TableCellEditor cellEditor = myTable.getCellEditor();
if (cellEditor != null) {
cellEditor.stopCellEditing();
}
processClose();
super.doCancelAction();
}
};
dialog.show();
}
@@ -75,6 +75,17 @@ public abstract class LookAheadLexer extends LexerBase{
return myBaseLexer.getBufferEnd();
}
protected int getCacheSize() {
return myTypeCache.size();
}
protected void resetCacheSize(int size) {
while (myTypeCache.size() > size) {
myTypeCache.removeLast();
myEndOffsetCache.removeLast();
}
}
public int getState() {
int offset = myTokenStart - myLastOffset;
return myLastState | (offset << 16);
@@ -18,6 +18,7 @@ package com.intellij.internal.statistic.connect;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.updateSettings.impl.UpdateChecker;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.net.HttpConfigurable;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
@@ -31,6 +32,8 @@ public class StatisticsHttpClientSender implements StatisticsDataSender {
PostMethod post = null;
try {
HttpConfigurable.getInstance().prepareURL(url);
HttpClient httpclient = new HttpClient();
post = new PostMethod(url);
@@ -1,10 +1,12 @@
package com.intellij.internal.statistic.updater;
import com.apple.eawt.Application;
import com.intellij.internal.statistic.connect.RemotelyConfigurableStatisticsService;
import com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent;
import com.intellij.internal.statistic.configurable.StatisticsConfigurable;
import com.intellij.notification.*;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
@@ -57,7 +59,12 @@ public class StatisticsNotificationManager {
mySettings.setShowNotification(false);
notification.expire();
myStatisticsService.send();
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
@Override
public void run() {
myStatisticsService.send();
}
});
}
else if ("decline".equals(description)) {
mySettings.setAllowed(false);
@@ -0,0 +1,115 @@
/*
* Copyright 2000-2011 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.openapi.editor.actions;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Allows to remove <a href="http://unicode.org/faq/utf_bom.html">file's BOM</a> (if any).
*
* @author Denis Zhdanov
* @since 3/30/11 11:14 AM
*/
public class RemoveBomAction extends AnAction implements DumbAware {
private static final Logger LOG = Logger.getInstance("#" + RemoveBomAction.class);
public RemoveBomAction() {
super("Remove BOM");
}
@Override
public void actionPerformed(AnActionEvent e) {
VirtualFile[] files = PlatformDataKeys.VIRTUAL_FILE_ARRAY.getData(e.getDataContext());
if (files == null) {
return;
}
List<VirtualFile> filesToProcess = getFilesWithBom(files, true);
for (VirtualFile virtualFile : filesToProcess) {
byte[] bom = virtualFile.getBOM();
assert bom != null;
if (virtualFile instanceof NewVirtualFile) {
virtualFile.setBOM(null);
NewVirtualFile file = (NewVirtualFile)virtualFile;
try {
byte[] bytes = file.contentsToByteArray();
byte[] contentWithStrippedBom = new byte[bytes.length - bom.length];
System.arraycopy(bytes, bom.length, contentWithStrippedBom, 0, contentWithStrippedBom.length);
file.setBinaryContent(contentWithStrippedBom);
}
catch (IOException ex) {
LOG.warn("Unexpected exception occurred on attempt to remove BOM from file " + file, ex);
}
}
}
}
@Override
public void update(AnActionEvent e) {
VirtualFile[] files = PlatformDataKeys.VIRTUAL_FILE_ARRAY.getData(e.getDataContext());
if (files == null) {
e.getPresentation().setEnabled(false);
return;
}
e.getPresentation().setEnabled(!getFilesWithBom(files, false).isEmpty());
}
/**
* Recursively traverses contents of the given file roots (any root may be directory) and returns files that have
* {@link VirtualFile#getBOM() BOM} defined.
*
* @param roots VFS roots to traverse
* @param all flag the defines if all files with {@link VirtualFile#getBOM() BOM} should be collected or just any of them
* @return collection of detected files with defined {@link VirtualFile#getBOM() BOM} if any; empty collectio otherwise
*/
@NotNull
private static List<VirtualFile> getFilesWithBom(@NotNull VirtualFile[] roots, boolean all) {
List<VirtualFile> result = new ArrayList<VirtualFile>();
for (VirtualFile root : roots) {
if (!all && !result.isEmpty()) {
break;
}
getFilesWithBom(root, result, all);
}
return result;
}
private static void getFilesWithBom(@NotNull VirtualFile root, @NotNull List<VirtualFile> result, boolean all) {
if (root.isDirectory()) {
for (VirtualFile child : root.getChildren()) {
if (!all && !result.isEmpty()) {
return;
}
getFilesWithBom(child, result, all);
}
}
else if (root.getBOM() != null) {
result.add(root);
}
}
}
@@ -56,7 +56,7 @@ import java.util.*;
*/
public class FileTypeManagerImpl extends FileTypeManagerEx implements NamedJDOMExternalizable, ExportableApplicationComponent {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl");
private static final int VERSION = 9;
private static final int VERSION = 10;
private final Set<FileType> myDefaultTypes = new THashSet<FileType>();
private final ArrayList<FileTypeIdentifiableByVirtualFile> mySpecialFileTypes = new ArrayList<FileTypeIdentifiableByVirtualFile>();
@@ -497,9 +497,13 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements NamedJDOME
addIgnore("*~");
}
if (savedVersion < VERSION) {
if (savedVersion < 9) {
addIgnore("__pycache__");
}
if (savedVersion < VERSION) {
addIgnore(".bundle");
}
}
private void readGlobalMappings(final Element e) {
@@ -211,6 +211,7 @@
<extensionPoint name="refactoring.moveHandler" interface="com.intellij.refactoring.move.MoveHandlerDelegate"/>
<extensionPoint name="refactoring.moveClassHandler" interface="com.intellij.refactoring.move.moveClassesOrPackages.MoveClassHandler"/>
<extensionPoint name="refactoring.moveMemberHandler" beanClass="com.intellij.lang.LanguageExtensionPoint"/>
<extensionPoint name="refactoring.moveInnerHandler" beanClass="com.intellij.lang.LanguageExtensionPoint"/>
<extensionPoint name="refactoring.helper" interface="com.intellij.refactoring.RefactoringHelper"/>
<extensionPoint name="refactoring.inlineHandler" beanClass="com.intellij.lang.LanguageExtensionPoint"/>
<extensionPoint name="refactoring.safeDeleteProcessor" interface="com.intellij.refactoring.safeDelete.SafeDeleteProcessorDelegate"/>
@@ -205,6 +205,9 @@
<action id="GotoTest">
<keyboard-shortcut first-keystroke="control shift T"/>
</action>
<action id="GotoRelated">
<keyboard-shortcut first-keystroke="control shift Q"/>
</action>
<action id="CloseActiveTab">
<keyboard-shortcut first-keystroke="control shift F4"/>
</action>
@@ -382,6 +382,9 @@
<action id="GotoLine">
<keyboard-shortcut first-keystroke="meta L"/>
</action>
<action id="GotoRelated">
<keyboard-shortcut first-keystroke="control meta UP"/>
</action>
<action id="QuickImplementations">
<keyboard-shortcut first-keystroke="alt SPACE"/>
<keyboard-shortcut first-keystroke="meta Y"/>
@@ -225,9 +225,7 @@
<action id="GotoTypeDeclaration" class="com.intellij.codeInsight.navigation.actions.GotoTypeDeclarationAction"/>
<action id="GotoSuperMethod" class="com.intellij.codeInsight.navigation.actions.GotoSuperAction"/>
<action id="GotoTest" class="com.intellij.testIntegration.GotoTestOrCodeAction"/>
<action id="GotoRelated" class="com.intellij.ide.actions.GotoRelatedFileAction" text="_Related File">
<keyboard-shortcut keymap="$default" first-keystroke="ctrl shift Q"/>
</action>
<action id="GotoRelated" class="com.intellij.ide.actions.GotoRelatedFileAction" text="_Related File"/>
<separator/>
<add-to-group group-id="GoToMenu" anchor="before" relative-to-action="GoToErrorGroup"/>
@@ -451,6 +449,8 @@
<reference ref="ExternalToolsGroup"/>
<separator/>
<reference ref="ProjectViewPopupMenuSettingsGroup"/>
<separator/>
<reference ref="RemoveBom"/>
</group>
<group id="NavbarPopupMenu">
@@ -143,6 +143,7 @@
<group id="ChangeFileEncodingGroup" popup="true" class="com.intellij.openapi.vfs.encoding.ChangeEncodingUpdateGroup">
<action id="ChangeFileEncodingGroupAction" class="com.intellij.openapi.vfs.encoding.ChangeFileEncodingGroup" text=""/>
</group>
<action id="RemoveBom" class="com.intellij.openapi.editor.actions.RemoveBomAction"/>
<action id="ToggleReadOnlyAttribute" class="com.intellij.ide.actions.ToggleReadOnlyAttributeAction"/>
<separator/>
<action id="Exit" class="com.intellij.ide.actions.ExitAction"/>
@@ -337,6 +338,8 @@
<separator/>
<action id="CompareClipboardWithSelection" class="com.intellij.openapi.diff.actions.CompareClipboardWithSelection"/>
<reference ref="ChangeFileEncodingGroup"/>
<separator/>
<reference ref="RemoveBom"/>
</group>
<group id="EditorTabPopupMenu">
@@ -213,7 +213,7 @@ public interface CodeInsightTestFixture extends IdeaProjectTestFixture {
PsiFile configureByFile(@TestDataFile @NonNls String file);
void configureByFiles(@TestDataFile @NonNls String... files);
PsiFile[] configureByFiles(@TestDataFile @NonNls String... files);
PsiFile configureByText(FileType fileType, @NonNls String text);
@@ -1107,13 +1107,15 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig
InspectionProjectProfileManager.getInstance(getProject()).setProjectProfile(profile.getName());
}
private void configureByFilesInner(@NonNls String... filePaths) {
private PsiFile[] configureByFilesInner(@NonNls String... filePaths) {
assertInitialized();
myFile = null;
myEditor = null;
PsiFile[] psiFiles = new PsiFile[filePaths.length];
for (int i = filePaths.length - 1; i >= 0; i--) {
configureByFileInner(filePaths[i]);
psiFiles[i] = configureByFileInner(filePaths[i]);
}
return psiFiles;
}
@Override
@@ -1124,8 +1126,8 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig
}
@Override
public void configureByFiles(@NonNls final String... files) {
configureByFilesInner(files);
public PsiFile[] configureByFiles(@NonNls final String... files) {
return configureByFilesInner(files);
}
@Override
@@ -101,7 +101,9 @@ class XmlSerializerImpl {
if (Number.class.isAssignableFrom(aClass)) return new PrimitiveValueBinding(aClass);
if (Boolean.class.isAssignableFrom(aClass)) return new PrimitiveValueBinding(aClass);
if (String.class.isAssignableFrom(aClass)) return new PrimitiveValueBinding(aClass);
if (Collection.class.isAssignableFrom(aClass)) return new CollectionBinding((ParameterizedType)originalType, this, accessor);
if (Collection.class.isAssignableFrom(aClass)) {
return new CollectionBinding((ParameterizedType)originalType, this, accessor);
}
if (Map.class.isAssignableFrom(aClass)) return new MapBinding((ParameterizedType)originalType, this, accessor);
if (Element.class.isAssignableFrom(aClass)) return new JDOMElementBinding(accessor);
if (Date.class.isAssignableFrom(aClass)) return new DateBinding();
@@ -112,6 +112,14 @@ public abstract class XDebuggerEvaluator {
return sideEffectsAllowed ? null : getExpressionRangeAtOffset(project, document, offset);
}
/**
* Override this method to format selected text before it is shown in 'Evaluate' dialog
*/
@NotNull
public String formatTextForEvaluation(@NotNull String text) {
return text;
}
/**
* @return delay before showing value tooltip (in ms)
*/
@@ -46,24 +46,28 @@ public class XDebuggerEvaluateActionHandler extends XDebuggerSuspendedActionHand
@Nullable Project project = PlatformDataKeys.PROJECT.getData(dataContext);
@Nullable Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
String expression = editor != null ? editor.getSelectionModel().getSelectedText() : null;
String selectedText = editor != null ? editor.getSelectionModel().getSelectedText() : null;
if (selectedText != null) {
selectedText = evaluator.formatTextForEvaluation(selectedText);
}
String text = selectedText;
if (expression == null && editor != null) {
if (text == null && editor != null) {
Document document = editor.getDocument();
TextRange range = evaluator.getExpressionRangeAtOffset(project, document, editor.getCaretModel().getOffset(), true);
expression = range == null ? null : document.getText(range);
text = range == null ? null : document.getText(range);
}
if (expression == null) {
if (text == null) {
XValue value = XDebuggerTreeActionBase.getSelectedValue(dataContext);
if (value != null) {
expression = value.getEvaluationExpression();
text = value.getEvaluationExpression();
}
}
if (expression == null) {
expression = "";
if (text == null) {
text = "";
}
final XDebuggerEvaluationDialog dialog = new XDebuggerEvaluationDialog(session, editorsProvider, evaluator, expression,
final XDebuggerEvaluationDialog dialog = new XDebuggerEvaluationDialog(session, editorsProvider, evaluator, text,
stackFrame.getSourcePosition());
dialog.show();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2003-2008 Dave Griffith, Bas Leijdekkers
* Copyright 2003-2011 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,18 +24,21 @@ import com.siyeh.ig.psiutils.TypeUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public class SafeLockInspection extends BaseInspection {
public class SafeLockInspection extends BaseInspection { // todo extend ResourceInspection?
@Override
@NotNull
public String getID() {
return "LockAcquiredButNotSafelyReleased";
}
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message("safe.lock.display.name");
}
@Override
@NotNull
public String buildErrorString(Object... infos) {
final PsiExpression expression = (PsiExpression)infos[0];
@@ -46,6 +49,7 @@ public class SafeLockInspection extends BaseInspection {
"safe.lock.problem.descriptor", text);
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new SafeLockVisitor();
}
@@ -60,17 +64,48 @@ public class SafeLockInspection extends BaseInspection {
}
final PsiReferenceExpression methodExpression =
expression.getMethodExpression();
final PsiExpression lhs = methodExpression.getQualifierExpression();
if (!(lhs instanceof PsiReferenceExpression)) {
final PsiExpression qualifierExpression =
methodExpression.getQualifierExpression();
final PsiVariable boundVariable;
final PsiReferenceExpression referenceExpression;
final LockType type;
if (qualifierExpression instanceof PsiReferenceExpression) {
referenceExpression = (PsiReferenceExpression) qualifierExpression;
final PsiElement target = referenceExpression.resolve();
if (!(target instanceof PsiVariable)) {
return;
}
boundVariable = (PsiVariable)target;
type = LockType.REGULAR;
} else if (qualifierExpression instanceof PsiMethodCallExpression) {
final PsiMethodCallExpression methodCallExpression =
(PsiMethodCallExpression) qualifierExpression;
final PsiReferenceExpression methodExpression1 =
methodCallExpression.getMethodExpression();
@NonNls final String methodName =
methodExpression1.getReferenceName();
if ("readLock".equals(methodName)) {
type = LockType.READ;
} else if ("writeLock".equals(methodName)) {
type = LockType.WRITE;
} else {
return;
}
final PsiExpression qualifierExpression1 =
methodExpression1.getQualifierExpression();
if (!(qualifierExpression1 instanceof PsiReferenceExpression)) {
return;
}
referenceExpression =
(PsiReferenceExpression) qualifierExpression1;
final PsiElement target = referenceExpression.resolve();
if (!(target instanceof PsiVariable)) {
return;
}
boundVariable = (PsiVariable) target;
} else {
return;
}
final PsiReferenceExpression referenceExpression =
(PsiReferenceExpression) lhs;
final PsiElement referent = referenceExpression.resolve();
if (referent == null || !(referent instanceof PsiVariable)) {
return;
}
final PsiVariable boundVariable = (PsiVariable)referent;
final PsiStatement statement =
PsiTreeUtil.getParentOfType(expression, PsiStatement.class);
if (statement == null) {
@@ -83,15 +118,17 @@ public class SafeLockInspection extends BaseInspection {
registerError(expression, referenceExpression);
return;
}
PsiTryStatement tryStatement = (PsiTryStatement) nextStatement;
if (lockIsUnlockedInFinally(tryStatement, boundVariable)) {
final PsiTryStatement tryStatement =
(PsiTryStatement) nextStatement;
if (lockIsUnlockedInFinally(tryStatement, boundVariable, type)) {
return;
}
registerError(expression, referenceExpression);
}
private static boolean lockIsUnlockedInFinally(
PsiTryStatement tryStatement, PsiVariable boundVariable) {
PsiTryStatement tryStatement, PsiVariable boundVariable,
LockType type) {
final PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
if (finallyBlock == null) {
return false;
@@ -100,9 +137,10 @@ public class SafeLockInspection extends BaseInspection {
if (tryBlock == null) {
return false;
}
final UnlockVisitor visitor = new UnlockVisitor(boundVariable);
final UnlockVisitor visitor =
new UnlockVisitor(boundVariable, type);
finallyBlock.accept(visitor);
return visitor.containsStreamClose();
return visitor.containsUnlock();
}
private static boolean isLockAcquireMethod(
@@ -121,29 +159,31 @@ public class SafeLockInspection extends BaseInspection {
return false;
}
return TypeUtils.expressionHasTypeOrSubtype(qualifier,
"java.util.concurrent.locks.Lock");
"java.util.concurrent.locks.Lock");
}
}
private static class UnlockVisitor extends JavaRecursiveElementVisitor {
private boolean containsClose = false;
private final PsiVariable objectToClose;
private boolean containsUnlock = false;
private final PsiVariable variable;
private final LockType type;
private UnlockVisitor(PsiVariable objectToClose) {
super();
this.objectToClose = objectToClose;
private UnlockVisitor(@NotNull PsiVariable variable,
@NotNull LockType type) {
this.variable = variable;
this.type = type;
}
@Override public void visitElement(@NotNull PsiElement element) {
if (!containsClose) {
if (!containsUnlock) {
super.visitElement(element);
}
}
@Override public void visitMethodCallExpression(
@NotNull PsiMethodCallExpression call) {
if (containsClose) {
if (containsUnlock) {
return;
}
super.visitMethodCallExpression(call);
@@ -156,21 +196,46 @@ public class SafeLockInspection extends BaseInspection {
}
final PsiExpression qualifier =
methodExpression.getQualifierExpression();
if (!(qualifier instanceof PsiReferenceExpression)) {
return;
}
final PsiElement referent =
((PsiReference)qualifier).resolve();
if (referent == null) {
return;
}
if (referent.equals(objectToClose)) {
containsClose = true;
if (qualifier instanceof PsiReferenceExpression) {
if (type != LockType.REGULAR) {
return;
}
final PsiReference reference = (PsiReference) qualifier;
final PsiElement target = reference.resolve();
if (variable.equals(target)) {
containsUnlock = true;
}
} else if (qualifier instanceof PsiMethodCallExpression) {
final PsiMethodCallExpression methodCallExpression =
(PsiMethodCallExpression) qualifier;
final PsiReferenceExpression methodExpression1 =
methodCallExpression.getMethodExpression();
@NonNls final String methodName1 =
methodExpression1.getReferenceName();
if (type == LockType.READ && "readLock".equals(methodName1) ||
type == LockType.WRITE &&
"writeLock".equals(methodName1)) {
final PsiExpression qualifierExpression =
methodExpression1.getQualifierExpression();
if (!(qualifierExpression instanceof PsiReferenceExpression)) {
return;
}
final PsiReferenceExpression referenceExpression =
(PsiReferenceExpression) qualifierExpression;
final PsiElement target = referenceExpression.resolve();
if (variable.equals(target)) {
containsUnlock = true;
}
}
}
}
public boolean containsStreamClose() {
return containsClose;
public boolean containsUnlock() {
return containsUnlock;
}
}
enum LockType {
READ, WRITE, REGULAR
}
}
@@ -237,4 +237,5 @@ android.sdk.configure.jdk.error=Please configure internal JDK
no.jdk.for.android.found.error=No Java SDK of appropriate version found. In addition to the Android SDK, you need to define a JSDK 1.5 or 1.6
no.jdk.error=You need to create at least one JSDK of versions 1.5 or 1.6
cannot.parse.sdk.error=Cannot parse Android SDK
android.add.sdk.tooltip=Add SDK
android.add.sdk.tooltip=Add SDK
android.console.tool.window.title=Android Console
@@ -79,6 +79,6 @@ public class RunAndroidSdkManagerAction extends AnAction {
}
GeneralCommandLine commandLine = new GeneralCommandLine();
commandLine.setExePath(sdkPath + File.separator + AndroidUtils.toolPath(SdkConstants.androidCmdName()));
AndroidUtils.runExternalToolInSeparateThread(project, commandLine, null);
AndroidUtils.runExternalToolInSeparateThread(project, commandLine);
}
}
@@ -319,7 +319,7 @@ public class AndroidFacet extends Facet<AndroidFacetConfiguration> {
return myAvdManager;
}
public void launchEmulator(@Nullable final String avdName, @NotNull final String commands, @Nullable final ProcessHandler handler) {
public void launchEmulator(@Nullable final String avdName, @NotNull final String commands) {
AndroidPlatform platform = getConfiguration().getAndroidPlatform();
if (platform != null) {
final String emulatorPath = platform.getSdk().getLocation() + File.separator + AndroidUtils.toolPath(EMULATOR);
@@ -335,7 +335,7 @@ public class AndroidFacet extends Facet<AndroidFacetConfiguration> {
commandLine.addParameter(s);
}
}
AndroidUtils.runExternalToolInSeparateThread(getModule().getProject(), commandLine, handler);
AndroidUtils.runExternalToolInSeparateThread(getModule().getProject(), commandLine);
}
}
@@ -33,10 +33,11 @@ public abstract class AndroidLoggingReader extends Reader {
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
Reader reader;
synchronized (getLock()) {
Reader reader = getReader();
return reader != null ? reader.read(cbuf, off, len) : -1;
reader = getReader();
}
return reader != null ? reader.read(cbuf, off, len) : -1;
}
@Override
@@ -22,6 +22,7 @@ import com.intellij.CommonBundle;
import com.intellij.execution.RunManagerEx;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.facet.FacetManager;
import com.intellij.facet.ModifiableFacetModel;
import com.intellij.ide.util.projectWizard.JavaModuleBuilder;
@@ -234,7 +235,8 @@ public class AndroidModuleBuilder extends JavaModuleBuilder {
@Override
public void run() {
final Project project = module.getProject();
final String result = AndroidUtils.runExternalTool(project, commandLine, null);
AndroidUtils.runExternalTool(project, commandLine, true);
StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() {
public void run() {
FileDocumentManager.getInstance().saveAllDocuments();
@@ -247,8 +249,8 @@ public class AndroidModuleBuilder extends JavaModuleBuilder {
public void run() {
if (contentRoot.findChild(SdkConstants.FN_ANDROID_MANIFEST_XML) == null) {
Messages.showErrorDialog(project, "The project wasn't generated by 'android' tool\n" + (result != null ? result : ""),
CommonBundle.getErrorTitle());
AndroidUtils.printMessageToConsole(project, "The project wasn't generated by 'android' tool.",
ConsoleViewContentType.ERROR_OUTPUT);
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@@ -356,14 +356,14 @@ public abstract class AndroidRunningState implements RunProfileState, AndroidDeb
chooseAvd();
}
if (myAvdName != null) {
myFacet.launchEmulator(myAvdName, myCommandLine, myProcessHandler);
myFacet.launchEmulator(myAvdName, myCommandLine);
}
else if (getProcessHandler().isStartNotified()) {
getProcessHandler().destroyProcess();
}
}
else {
myFacet.launchEmulator(myAvdName, myCommandLine, myProcessHandler);
myFacet.launchEmulator(myAvdName, myCommandLine);
}
}
}
@@ -116,7 +116,7 @@ public class AvdChooser extends DialogWrapper {
public void actionPerformed(ActionEvent e) {
GeneralCommandLine commandLine = new GeneralCommandLine();
commandLine.setExePath(androidToolPath);
AndroidUtils.runExternalToolInSeparateThread(project, commandLine, null);
AndroidUtils.runExternalToolInSeparateThread(project, commandLine);
}
});
updateTable();
@@ -221,7 +221,7 @@ public class DeviceChooser extends DialogWrapper implements AndroidDebugBridge.I
if (chooser.getExitCode() != OK_EXIT_CODE) return;
if (avd == null) return;
}
myFacet.launchEmulator(avd != null ? avd.getName() : null, "", null);
myFacet.launchEmulator(avd != null ? avd.getName() : null, "");
}
}
@@ -273,7 +273,7 @@ public abstract class AndroidSdk {
private volatile boolean myCanceled;
public MyInitializeDdmlibTask(Project project) {
super(project, "Connecting to ADB process", true);
super(project, "Waiting for ADB", true);
}
public boolean isFinished() {
@@ -70,7 +70,7 @@ public class AndroidSdkImpl extends AndroidSdk {
@Override
public IAndroidTarget findTargetByHashString(@NotNull String hashString) {
return mySdkManager.getTargetFromHashString(hashString);
return new MyTargetWrapper(mySdkManager.getTargetFromHashString(hashString));
}
@NotNull
@@ -29,7 +29,10 @@ import com.intellij.execution.ExecutionException;
import com.intellij.execution.RunManagerEx;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.impl.ConsoleViewImpl;
import com.intellij.execution.process.*;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.ide.util.DefaultPsiElementCellRenderer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
@@ -53,12 +56,20 @@ import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.ex.ToolWindowManagerEx;
import com.intellij.openapi.wm.ex.ToolWindowManagerListener;
import com.intellij.psi.*;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManagerAdapter;
import com.intellij.ui.content.impl.ContentImpl;
import com.intellij.util.PsiNavigateUtil;
import com.intellij.util.containers.HashSet;
import com.intellij.util.ui.UIUtil;
@@ -125,6 +136,8 @@ public class AndroidUtils {
public static final int TIMEOUT = 300000;
private static final Key<ConsoleView> CONSOLE_VIEW_KEY = new Key<ConsoleView>("AndroidConsoleView");
private AndroidUtils() {
}
@@ -432,25 +445,19 @@ public class AndroidUtils {
}
public static void runExternalToolInSeparateThread(@NotNull final Project project,
@NotNull final GeneralCommandLine commandLine,
@Nullable final ProcessHandler processHandler) {
@NotNull final GeneralCommandLine commandLine) {
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
runExternalTool(project, commandLine, processHandler);
runExternalTool(project, commandLine, false);
}
});
}
@Nullable
public static String runExternalTool(final Project project,
GeneralCommandLine commandLine,
ProcessHandler processHandler) {
public static void runExternalTool(final Project project, GeneralCommandLine commandLine, boolean printOutputToConsole) {
String[] commands = commandLine.getCommands();
String command = StringUtil.join(commands, " ");
LOG.info("Execute: " + command);
if (processHandler != null && !processHandler.isProcessTerminated()) {
processHandler.notifyTextAvailable(command + '\n', ProcessOutputTypes.STDOUT);
}
StringBuilder messageBuilder = new StringBuilder();
String result;
boolean success = false;
@@ -461,21 +468,19 @@ public class AndroidUtils {
catch (ExecutionException e) {
result = e.getMessage();
}
if (result != null && !success) {
final String errorMessage = result;
if (processHandler != null) {
processHandler.notifyTextAvailable(errorMessage + '\n', ProcessOutputTypes.STDERR);
processHandler.destroyProcess();
}
else {
UIUtil.invokeLaterIfNeeded(new Runnable() {
public void run() {
Messages.showErrorDialog(project, errorMessage, AndroidBundle.message("emulator.error.dialog.title"));
}
});
}
if (result != null && printOutputToConsole) {
final ConsoleViewContentType contentType = success ?
ConsoleViewContentType.NORMAL_OUTPUT :
ConsoleViewContentType.ERROR_OUTPUT;
final String finalResult = result;
UIUtil.invokeLaterIfNeeded(new Runnable() {
@Override
public void run() {
printMessageToConsole(project, finalResult, contentType);
}
});
}
return result;
}
public static String getSimpleNameByRelativePath(String relativePath) {
@@ -589,4 +594,50 @@ public class AndroidUtils {
}
}
}
public static void printMessageToConsole(@NotNull Project project, @NotNull String s, @NotNull ConsoleViewContentType contentType) {
activateConsoleToolWindow(project);
final ConsoleView consoleView = project.getUserData(CONSOLE_VIEW_KEY);
if (consoleView != null) {
consoleView .print(s + '\n', contentType);
}
}
private static void activateConsoleToolWindow(@NotNull Project project) {
final ToolWindowManager manager = ToolWindowManager.getInstance(project);
final String toolWindowId = AndroidBundle.message("android.console.tool.window.title");
ToolWindow toolWindow = manager.getToolWindow(toolWindowId);
if (toolWindow != null) {
return;
}
toolWindow = manager.registerToolWindow(toolWindowId, true, ToolWindowAnchor.BOTTOM);
final ConsoleView console = new ConsoleViewImpl(project, false);
project.putUserData(CONSOLE_VIEW_KEY, console);
toolWindow.getContentManager().addContent(new ContentImpl(console.getComponent(), "", false));
final ToolWindowManagerListener listener = new ToolWindowManagerListener() {
@Override
public void toolWindowRegistered(@NotNull String id) {
}
@Override
public void stateChanged() {
ToolWindow window = manager.getToolWindow(toolWindowId);
if (window != null && !window.isVisible()) {
manager.unregisterToolWindow(toolWindowId);
((ToolWindowManagerEx)manager).removeToolWindowManagerListener(this);
}
}
};
toolWindow.show(new Runnable() {
@Override
public void run() {
((ToolWindowManagerEx)manager).addToolWindowManagerListener(listener);
}
});
}
}
+1 -1
View File
@@ -174,7 +174,7 @@
<lang.refactoringSupport language="Groovy"
implementationClass="org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringSupportProvider"/>
<lang.surroundDescriptor language="Groovy"
implementationClass="org.jetbrains.plugins.groovy.lang.surroundWith.descriptors.GroovyStmtsSurroundDescriptor"/>
implementationClass="org.jetbrains.plugins.groovy.lang.surroundWith.GroovySurroundDescriptor"/>
<lang.findUsagesProvider language="Groovy" implementationClass="org.jetbrains.plugins.groovy.findUsages.GroovyFindUsagesProvider"/>
<readWriteAccessDetector implementation="org.jetbrains.plugins.groovy.findUsages.GroovyReadWriteAccessDetector" order="before java"/>
<findUsagesHandlerFactory implementation="org.jetbrains.plugins.groovy.findUsages.GroovyFindUsagesHandlerFactory"/>
@@ -36,6 +36,11 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefini
import org.jetbrains.plugins.groovy.util.LibrariesUtil;
public class NewGroovyClassAction extends JavaCreateTemplateInPackageAction<GrTypeDefinition> implements DumbAware {
public static final String GROOVY_CLASS = "GroovyClass.groovy";
public static final String GROOVY_INTERFACE = "GroovyInterface.groovy";
public static final String GROOVY_ENUM = "GroovyEnum.groovy";
public static final String GROOVY_ANNOTATION = "GroovyAnnotation.groovy";
public NewGroovyClassAction() {
super(GroovyBundle.message("newclass.menu.action.text"), GroovyBundle.message("newclass.menu.action.description"), GroovyIcons.CLASS, true);
}
@@ -44,10 +49,10 @@ public class NewGroovyClassAction extends JavaCreateTemplateInPackageAction<GrTy
protected void buildDialog(Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder) {
builder
.setTitle(GroovyBundle.message("newclass.dlg.title"))
.addKind("Class", GroovyIcons.CLASS, "GroovyClass.groovy")
.addKind("Interface", GroovyIcons.INTERFACE, "GroovyInterface.groovy")
.addKind("Enum", GroovyIcons.ENUM, "GroovyEnum.groovy")
.addKind("Annotation", GroovyIcons.ANNOTATION_TYPE, "GroovyAnnotation.groovy");
.addKind("Class", GroovyIcons.CLASS, GROOVY_CLASS)
.addKind("Interface", GroovyIcons.INTERFACE, GROOVY_INTERFACE)
.addKind("Enum", GroovyIcons.ENUM, GROOVY_ENUM)
.addKind("Annotation", GroovyIcons.ANNOTATION_TYPE, GROOVY_ANNOTATION);
}
@Override
@@ -64,16 +64,16 @@ public abstract class CreateClassActionBase implements IntentionAction {
}
public static PsiClass createClassByType(final PsiDirectory directory,
final String name,
final PsiManager manager,
final PsiElement contextElement) {
final String name,
final PsiManager manager,
final PsiElement contextElement, final String templateName) {
return ApplicationManager.getApplication().runWriteAction(
new Computable<PsiClass>() {
public PsiClass compute() {
try {
PsiClass targetClass = null;
try {
PsiFile file = GroovyTemplatesFactory.createFromTemplate(directory, name, name + ".groovy", "GroovyClass.groovy");
PsiFile file = GroovyTemplatesFactory.createFromTemplate(directory, name, name + ".groovy", templateName);
for (PsiElement element : file.getChildren()) {
if (element instanceof PsiClass) {
targetClass = ((PsiClass) element);
@@ -26,6 +26,7 @@ import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.actions.NewGroovyClassAction;
import org.jetbrains.plugins.groovy.intentions.base.IntentionUtils;
import org.jetbrains.plugins.groovy.lang.editor.template.expressions.ChooseTypeExpression;
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement;
@@ -34,6 +35,7 @@ import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrImplementsClause;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrMemberOwner;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.SupertypeConstraint;
@@ -61,7 +63,7 @@ public abstract class CreateClassFix {
PsiDirectory targetDirectory = getTargetDirectory(project, qualifier, name, module);
if (targetDirectory == null) return;
PsiClass targetClass = createClassByType(targetDirectory, name, manager, myRefElement);
PsiClass targetClass = createClassByType(targetDirectory, name, manager, myRefElement, NewGroovyClassAction.GROOVY_CLASS);
GrArgumentList argList = expression.getArgumentList();
if (argList != null &&
@@ -109,7 +111,8 @@ public abstract class CreateClassFix {
PsiDirectory targetDirectory = getTargetDirectory(project, qualifier, name, module);
if (targetDirectory == null) return;
PsiClass targetClass = createClassByType(targetDirectory, name, manager, myRefElement);
String templateName = myRefElement.getParent() instanceof GrImplementsClause ? NewGroovyClassAction.GROOVY_INTERFACE : NewGroovyClassAction.GROOVY_CLASS;
PsiClass targetClass = createClassByType(targetDirectory, name, manager, myRefElement, templateName);
if (targetClass != null) {
addImportForClass(groovyFile, qualifier, targetClass);
putCursor(project, targetClass.getContainingFile(), targetClass);
@@ -32,6 +32,7 @@ import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.actions.NewGroovyClassAction;
import org.jetbrains.plugins.groovy.annotator.intentions.CreateClassActionBase;
import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils;
import org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle;
@@ -93,7 +94,7 @@ public class ConvertMapToClassIntention extends Intention {
final GrTypeDefinition typeDefinition = createClass(project, namedArguments, selectedPackageName, shortName);
final PsiClass generatedClass = CreateClassActionBase.createClassByType(
dialog.getTargetDirectory(), typeDefinition.getName(), PsiManager.getInstance(project), map);
dialog.getTargetDirectory(), typeDefinition.getName(), PsiManager.getInstance(project), map, NewGroovyClassAction.GROOVY_CLASS);
final PsiClass replaced = (PsiClass)generatedClass.replace(typeDefinition);
replaceMapWithClass(project, map, replaced, replaceReturnType, variableDeclaration, methodParameter);
}
@@ -20,6 +20,7 @@ import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.jetbrains.plugins.groovy.lang.groovydoc.parser.GroovyDocElementTypes;
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
/**
* Interface that contains all tokens returned by GroovyLexer
@@ -228,7 +229,7 @@ public interface GroovyTokenTypes extends GroovyDocElementTypes {
TokenSet BINARY_OP_SET =
TokenSet.create(mBAND, mBOR, mBXOR, mDIV, mEQUAL, mGE, mGT, mLAND, mLOR, mLT, mLE, mMINUS, mMOD, mPLUS, mSTAR, mSTAR_STAR, mNOT_EQUAL,
mCOMPARE_TO);
mCOMPARE_TO, GroovyElementTypes.COMPOSITE_SHIFT_SIGN);
TokenSet DOTS = TokenSet.create(mSPREAD_DOT, mOPTIONAL_DOT, mMEMBER_POINTER, mDOT);
@@ -723,7 +723,8 @@ public class ControlFlowBuilder extends GroovyRecursiveElementVisitor {
public void visitVariable(GrVariable variable) {
super.visitVariable(variable);
if (variable.getInitializerGroovy() != null) {
if (variable.getInitializerGroovy() != null ||
variable.getParent() instanceof GrTupleDeclaration && ((GrTupleDeclaration)variable.getParent()).getInitializerGroovy() != null) {
ReadWriteVariableInstructionImpl writeInsn = new ReadWriteVariableInstructionImpl(variable, myInstructionNumber++);
checkPending(writeInsn);
addNode(writeInsn);
@@ -0,0 +1,54 @@
/*
* Copyright 2000-2011 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.plugins.groovy.lang.surroundWith;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrForStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForClause;
/**
* User: Dmitry.Krasilschikov
* Date: 25.05.2007
*/
public class ForSurrounder extends GroovyManyStatementsSurrounder {
protected GroovyPsiElement doSurroundElements(PsiElement[] elements) throws IncorrectOperationException {
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(elements[0].getProject());
GrForStatement whileStatement = (GrForStatement) factory.createTopElementFromText("for(a in b){\n}");
addStatements(((GrBlockStatement) whileStatement.getBody()).getBlock(), elements);
return whileStatement;
}
protected TextRange getSurroundSelectionRange(GroovyPsiElement element) {
assert element instanceof GrForStatement;
GrForClause clause = ((GrForStatement) element).getClause();
int endOffset = element.getTextRange().getEndOffset();
if (clause != null) {
endOffset = clause.getTextRange().getStartOffset();
clause.getParent().getNode().removeChild(clause.getNode());
}
return new TextRange(endOffset, endOffset);
}
public String getTemplateDescription() {
return "for";
}
}
@@ -13,9 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.conditions;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.GroovyExpressionSurrounder;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import com.intellij.psi.*;
@@ -23,13 +22,11 @@ import com.intellij.psi.*;
* User: Dmitry.Krasilschikov
* Date: 30.07.2007
*/
abstract class GroovyConditionSurrounder extends GroovyExpressionSurrounder {
public abstract class GroovyConditionSurrounder extends GroovyExpressionSurrounder {
protected boolean isApplicable(PsiElement element) {
if (! (element instanceof GrExpression)) return false;
GrExpression expression = (GrExpression) element;
PsiType type = expression.getType();
if (!GroovyManyStatementsSurrounder.isStatement(element) || !(element instanceof GrExpression)) return false;
PsiType type = ((GrExpression)element).getType();
return PsiType.BOOLEAN.equals(type) || PsiType.BOOLEAN.equals(PsiPrimitiveType.getUnboxedType(type));
}
}
@@ -13,8 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.lang.surroundWith.Surrounder;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
@@ -23,13 +24,12 @@ import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.GroovySingleElementSurrounder;
/**
* User: Dmitry.Krasilschikov
* Date: 22.05.2007
*/
public abstract class GroovyExpressionSurrounder extends GroovySingleElementSurrounder {
public abstract class GroovyExpressionSurrounder implements Surrounder {
protected boolean isApplicable(PsiElement element) {
return element instanceof GrExpression;
}
@@ -45,7 +45,11 @@ public abstract class GroovyExpressionSurrounder extends GroovySingleElementSurr
protected abstract TextRange surroundExpression(GrExpression expression);
protected void replaceToOldExpression(GrExpression oldExpr, GrExpression replacement) {
public boolean isApplicable(@NotNull PsiElement[] elements) {
return elements.length == 1 && isApplicable(elements[0]);
}
protected static void replaceToOldExpression(GrExpression oldExpr, GrExpression replacement) {
oldExpr.replaceWithExpression(replacement, false);
}
}
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.lang.ASTNode;
import com.intellij.lang.surroundWith.Surrounder;
@@ -21,43 +21,44 @@ import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner;
/**
* User: Dmitry.Krasilschikov
* Date: 22.05.2007
*/
public abstract class GroovyManyStatementsSurrounder implements Surrounder {
public boolean isStatements(@NotNull PsiElement[] elements) {
for (PsiElement element : elements) {
if (!(element instanceof GrStatement)) {
return false;
}
}
return true;
}
public boolean isApplicable(@NotNull PsiElement[] elements) {
if (elements.length == 0) return false;
if (elements.length == 1) return elements[0] instanceof GrStatement && !(elements[0] instanceof GrBlockStatement);
return isStatements(elements);
for (PsiElement element : elements) {
if (!isStatement(element)) return false;
}
if (elements[0] instanceof GrBlockStatement) {
return false;
}
return true;
}
protected String getListElementsTemplateAsString(PsiElement... elements) {
StringBuffer result = new StringBuffer();
for (PsiElement element : elements) {
result.append(element.getText());
result.append("\n");
public static boolean isStatement(PsiElement element) {
if (!(element instanceof GrStatement)) {
return false;
}
return result.toString();
PsiElement parent = element.getParent();
if (!(parent instanceof GrStatementOwner)) {
return false;
}
return true;
}
@Nullable
@@ -69,41 +70,17 @@ public abstract class GroovyManyStatementsSurrounder implements Surrounder {
assert newStmt != null;
ASTNode parentNode = element1.getParent().getNode();
for (int i = 0; i < elements.length; i++) {
PsiElement element = elements[i];
if (i == 0) {
parentNode.replaceChild(element1.getNode(), newStmt.getNode());
} else {
if (parentNode != element.getParent().getNode()) return null;
final int endOffset = element.getTextRange().getEndOffset();
final PsiElement semicolon = PsiTreeUtil.findElementOfClassAtRange(element.getContainingFile(), endOffset, endOffset + 1, PsiElement.class);
if (semicolon != null && ";".equals(semicolon.getText())) {
assert parentNode == semicolon.getParent().getNode();
parentNode.removeChild(semicolon.getNode());
}
if (i < elements.length - 1) {
final PsiElement newLine = PsiTreeUtil.findElementOfClassAtRange(element.getContainingFile(), endOffset, elements[i + 1].getTextRange().getStartOffset(), PsiElement.class);
if (newLine != null && GroovyElementTypes.mNLS.equals(newLine.getNode().getElementType())) {
assert parentNode == newLine.getParent().getNode();
parentNode.removeChild(newLine.getNode());
}
}
parentNode.removeChild(element.getNode());
}
if (elements.length > 1) {
parentNode.removeRange(element1.getNode().getTreeNext(), elements[elements.length - 1].getNode().getTreeNext());
}
parentNode.replaceChild(element1.getNode(), newStmt.getNode());
return getSurroundSelectionRange(newStmt);
}
protected void addStatements(GrCodeBlock block, PsiElement[] elements) throws IncorrectOperationException {
for (int i = 0; i < elements.length; i++) {
PsiElement element = elements[i];
final GrStatement statement = (GrStatement) element;
protected static void addStatements(GrCodeBlock block, PsiElement[] elements) throws IncorrectOperationException {
for (PsiElement element : elements) {
final GrStatement statement = (GrStatement)element;
block.addStatementBefore(statement, null);
}
}
@@ -13,9 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.GroovyManyStatementsSurrounder;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression;
@@ -13,10 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.descriptors;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.lang.ASTNode;
import com.intellij.lang.surroundWith.SurroundDescriptor;
import com.intellij.lang.surroundWith.Surrounder;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
@@ -34,7 +35,39 @@ import java.util.List;
* User: Dmitry.Krasilschikov
* Date: 22.05.2007
*/
public abstract class GroovySurroundDescriptor implements SurroundDescriptor {
public class GroovySurroundDescriptor implements SurroundDescriptor {
private static final Surrounder[] ourSurrounders = new Surrounder[]{
//statements: like in java
new IfSurrounder(),
new IfElseSurrounder(),
new WhileSurrounder(),
//there's no do-while in Groovy
new SurrounderByClosure(),
//like in Java
new ForSurrounder(),
new TryCatchSurrounder(),
new TryFinallySurrounder(),
new TryCatchFinallySurrounder(),
//groovy-specific statements
new ShouldFailWithTypeStatementsSurrounder(),
//expressions: like in java
new ParenthesisExprSurrounder(),
new TypeCastSurrounder(),
//groovy-specific
new WithStatementsSurrounder(),
new IfExprSurrounder(),
new IfElseExprSurrounder(),
new WhileExprSurrounder(),
new WithExprSurrounder(),
};
@NotNull
public Surrounder[] getSurrounders() {
return ourSurrounders;
}
@NotNull
public PsiElement[] getElementsToSurround(PsiFile file, int startOffset, int endOffset) {
GrStatement[] statements = findStatementsInRange(file, startOffset, endOffset);
@@ -44,7 +77,7 @@ public abstract class GroovySurroundDescriptor implements SurroundDescriptor {
}
@Nullable
private GrStatement[] findStatementsInRange(PsiFile file, int startOffset, int endOffset) {
private static GrStatement[] findStatementsInRange(PsiFile file, int startOffset, int endOffset) {
GrStatement statement;
int endOffsetLocal = endOffset;
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.conditions;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
@@ -26,7 +26,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpres
* User: Dmitry.Krasilschikov
* Date: 25.05.2007
*/
public class GroovyWithIfElseExprSurrounder extends GroovyConditionSurrounder {
public class IfElseExprSurrounder extends GroovyConditionSurrounder {
protected TextRange surroundExpression(GrExpression expression) {
GrIfStatement ifStatement = (GrIfStatement) GroovyPsiElementFactory.getInstance(expression.getProject()).createTopElementFromText("if(a){4\n} else{\n}");
replaceToOldExpression((GrExpression) ifStatement.getCondition(), expression);
@@ -46,6 +46,6 @@ public class GroovyWithIfElseExprSurrounder extends GroovyConditionSurrounder {
}
public String getTemplateDescription() {
return "if (...) / else";
return "if (expr) / else";
}
}
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
@@ -26,7 +26,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement;
* User: Dmitry.Krasilschikov
* Date: 25.05.2007
*/
public class GroovyWithIfElseSurrounder extends GroovyWithIfSurrounder {
public class IfElseSurrounder extends IfSurrounder {
@Override
protected GroovyPsiElement doSurroundElements(PsiElement[] elements) throws IncorrectOperationException {
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(elements[0].getProject());
@@ -37,6 +37,6 @@ public class GroovyWithIfElseSurrounder extends GroovyWithIfSurrounder {
@Override
public String getTemplateDescription() {
return super.getTemplateDescription() + " / else";
return "if / else";
}
}
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.conditions;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
@@ -26,7 +26,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpres
* User: Dmitry.Krasilschikov
* Date: 25.05.2007
*/
public class GroovyWithIfExprSurrounder extends GroovyConditionSurrounder {
public class IfExprSurrounder extends GroovyConditionSurrounder {
protected TextRange surroundExpression(GrExpression expression) {
GrIfStatement ifStatement = (GrIfStatement) GroovyPsiElementFactory.getInstance(expression.getProject()).createTopElementFromText("if(a){4\n}");
replaceToOldExpression((GrExpression)ifStatement.getCondition(), expression);
@@ -45,6 +45,6 @@ public class GroovyWithIfExprSurrounder extends GroovyConditionSurrounder {
}
public String getTemplateDescription() {
return "if (...) {}";
return "if (expr)";
}
}
@@ -13,26 +13,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiType;
import com.intellij.psi.PsiPrimitiveType;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.*;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrCondition;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.GroovyManyStatementsSurrounder;
import org.jetbrains.annotations.NotNull;
/**
* User: Dmitry.Krasilschikov
* Date: 23.05.2007
*/
public class GroovyWithIfSurrounder extends GroovyManyStatementsSurrounder {
public class IfSurrounder extends GroovyManyStatementsSurrounder {
protected GroovyPsiElement doSurroundElements(PsiElement[] elements) throws IncorrectOperationException {
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(elements[0].getProject());
GrIfStatement ifStatement = (GrIfStatement) factory.createTopElementFromText("if (a) {\n}");
@@ -56,18 +51,7 @@ public class GroovyWithIfSurrounder extends GroovyManyStatementsSurrounder {
}
public String getTemplateDescription() {
return "if () {...}";
return "if";
}
public boolean isApplicable(@NotNull PsiElement[] elements) {
if (!super.isApplicable(elements)) return false;
if (elements.length == 1 && elements[0] instanceof GrStatement) {
if (elements[0] instanceof GrExpression) {
PsiType type = ((GrExpression) elements[0]).getType();
return type == null || !((PsiPrimitiveType) PsiType.BOOLEAN).getBoxedTypeName().equals(type.getCanonicalText());
}
}
return true;
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
@@ -25,7 +25,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrParent
* User: Dmitry.Krasilschikov
* Date: 22.05.2007
*/
public class GroovyWithParenthesisExprSurrounder extends GroovyExpressionSurrounder {
public class ParenthesisExprSurrounder extends GroovyExpressionSurrounder {
protected TextRange surroundExpression(GrExpression expression) {
GrParenthesizedExpression result = (GrParenthesizedExpression) GroovyPsiElementFactory.getInstance(expression.getProject()).createExpressionFromText("(a)");
replaceToOldExpression(result.getOperand(), expression);
@@ -34,6 +34,6 @@ public class GroovyWithParenthesisExprSurrounder extends GroovyExpressionSurroun
}
public String getTemplateDescription() {
return "(...)";
return "(expr)";
}
}
@@ -13,14 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open;
package org.jetbrains.plugins.groovy.lang.surroundWith;
/**
* Provides the shouldFail() { ... } surround with. It follows a Template Method pattern.
* @author Hamlet D'Arcy
* @since 03.02.2009
*/
public class GroovyWithShouldFailWithTypeStatementsSurrounder extends GroovySimpleManyStatementsSurrounder {
public class ShouldFailWithTypeStatementsSurrounder extends GroovySimpleManyStatementsSurrounder {
protected String getReplacementTokens() {
return "shouldFail(a){\n}";
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
@@ -31,7 +31,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrM
* User: Dmitry.Krasilschikov
* Date: 22.05.2007
*/
public class GroovySurrounderByClosure extends GroovyManyStatementsSurrounder {
public class SurrounderByClosure extends GroovyManyStatementsSurrounder {
private static final Key<GroovyResolveResult> REF_RESOLVE_RESULT_KEY = Key.create("REF_RESOLVE_RESULT");
public String getTemplateDescription() {
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
@@ -25,7 +25,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrTryCatchStatement;
* User: Dmitry.Krasilschikov
* Date: 22.05.2007
*/
public class GroovyWithTryCatchFinallySurrounder extends GroovyWithTryCatchSurrounder {
public class TryCatchFinallySurrounder extends TryCatchSurrounder {
public String getTemplateDescription() {
return super.getTemplateDescription() + " / finally";
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
@@ -25,7 +25,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.*;
* User: Dmitry.Krasilschikov
* Date: 22.05.2007
*/
public class GroovyWithTryCatchSurrounder extends GroovyWithTrySurrounder {
public class TryCatchSurrounder extends TrySurrounder {
public String getTemplateDescription() {
return super.getTemplateDescription() + " / catch";
}
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;
@@ -25,7 +25,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrTryCatchStatement;
* User: Dmitry.Krasilschikov
* Date: 22.05.2007
*/
public class GroovyWithTryFinallySurrounder extends GroovyWithTrySurrounder {
public class TryFinallySurrounder extends TrySurrounder {
protected GroovyPsiElement doSurroundElements(PsiElement[] elements) throws IncorrectOperationException {
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(elements[0].getProject());
GrTryCatchStatement tryStatement = (GrTryCatchStatement) factory.createTopElementFromText("try {\n} finally{\n}");
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrTryCatchStatement;
@@ -22,13 +22,12 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.GroovyManyStatementsSurrounder;
/**
* User: Dmitry.Krasilschikov
* Date: 22.05.2007
*/
public abstract class GroovyWithTrySurrounder extends GroovyManyStatementsSurrounder {
public abstract class TrySurrounder extends GroovyManyStatementsSurrounder {
protected TextRange getSurroundSelectionRange(GroovyPsiElement element) {
assert element instanceof GrTryCatchStatement;
int endOffset = element.getTextRange().getEndOffset();
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
@@ -26,13 +26,13 @@ import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement;
* User: Dmitry.Krasilschikov
* Date: 25.05.2007
*/
public class GroovyWithTypeCastSurrounder extends GroovyExpressionSurrounder {
public class TypeCastSurrounder extends GroovyExpressionSurrounder {
protected TextRange surroundExpression(GrExpression expression) {
GrParenthesizedExpression parenthesized = (GrParenthesizedExpression) GroovyPsiElementFactory.getInstance(expression.getProject()).createTopElementFromText("((Type)a)");
GrTypeCastExpression typeCast = (GrTypeCastExpression) parenthesized.getOperand();
replaceToOldExpression(typeCast.getOperand(), expression);
GrTypeElement typeElement = typeCast.getCastTypeElement();
int endOffset = typeElement.getTextRange().getStartOffset();
int endOffset = typeElement.getTextRange().getStartOffset() + expression.getTextRange().getStartOffset();
parenthesized = (GrParenthesizedExpression) expression.replaceWithExpression(parenthesized, false);
final GrTypeCastExpression newTypeCast = (GrTypeCastExpression)parenthesized.getOperand();
@@ -42,6 +42,6 @@ public class GroovyWithTypeCastSurrounder extends GroovyExpressionSurrounder {
}
public String getTemplateDescription() {
return "((Type) ...)";
return "((Type) expr)";
}
}
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.conditions;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
@@ -26,7 +26,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpres
* User: Dmitry.Krasilschikov
* Date: 25.05.2007
*/
public class GroovyWithWhileExprSurrounder extends GroovyConditionSurrounder {
public class WhileExprSurrounder extends GroovyConditionSurrounder {
protected TextRange surroundExpression(GrExpression expression) {
GrWhileStatement whileStatement = (GrWhileStatement) GroovyPsiElementFactory.getInstance(expression.getProject()).createTopElementFromText("while(a){4\n}");
replaceToOldExpression((GrExpression)whileStatement.getCondition(), expression);
@@ -45,6 +45,6 @@ public class GroovyWithWhileExprSurrounder extends GroovyConditionSurrounder {
}
public String getTemplateDescription() {
return "while (...) {}";
return "while (expr)";
}
}
@@ -13,26 +13,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiPrimitiveType;
import com.intellij.psi.PsiType;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrCondition;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.*;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.GroovyManyStatementsSurrounder;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrWhileStatement;
/**
* User: Dmitry.Krasilschikov
* Date: 25.05.2007
*/
public class GroovyWithWhileSurrounder extends GroovyManyStatementsSurrounder {
public class WhileSurrounder extends GroovyManyStatementsSurrounder {
protected GroovyPsiElement doSurroundElements(PsiElement[] elements) throws IncorrectOperationException {
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(elements[0].getProject());
GrWhileStatement whileStatement = (GrWhileStatement) factory.createTopElementFromText("while(a){\n}");
@@ -52,18 +48,7 @@ public class GroovyWithWhileSurrounder extends GroovyManyStatementsSurrounder {
return new TextRange(endOffset, endOffset);
}
public boolean isApplicable(@NotNull PsiElement[] elements) {
if (!super.isApplicable(elements)) return false;
if (elements.length == 1 && elements[0] instanceof GrStatement) {
if (elements[0] instanceof GrExpression) {
PsiType type = ((GrExpression) elements[0]).getType();
return type == null || !((PsiPrimitiveType) PsiType.BOOLEAN).getBoxedTypeName().equals(type.getCanonicalText());
}
}
return true;
}
public String getTemplateDescription() {
return "while () {...}";
return "while";
}
}
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions;
package org.jetbrains.plugins.groovy.lang.surroundWith;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
@@ -21,12 +21,13 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression;
import org.jetbrains.plugins.groovy.lang.surroundWith.GroovyConditionSurrounder;
/**
* User: Dmitry.Krasilschikov
* Date: 25.05.2007
*/
public class GroovyWithWithExprSurrounder extends GroovyExpressionSurrounder {
public class WithExprSurrounder extends GroovyConditionSurrounder {
protected TextRange surroundExpression(GrExpression expression) {
GrMethodCallExpression call = (GrMethodCallExpression) GroovyPsiElementFactory.getInstance(expression.getProject()).createTopElementFromText("with(a){4\n}");
replaceToOldExpression(call.getExpressionArguments()[0], expression);
@@ -42,6 +43,6 @@ public class GroovyWithWithExprSurrounder extends GroovyExpressionSurrounder {
}
public String getTemplateDescription() {
return "with (...)";
return "with (expr)";
}
}
@@ -13,13 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open;
package org.jetbrains.plugins.groovy.lang.surroundWith;
/**
* User: Dmitry.Krasilschikov
* Date: 25.05.2007
*/
public class GroovyWithWithStatementsSurrounder extends GroovySimpleManyStatementsSurrounder {
public class WithStatementsSurrounder extends GroovySimpleManyStatementsSurrounder {
protected String getReplacementTokens() {
return "with(a){\n}";
@@ -1,82 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.surroundWith.descriptors;
import com.intellij.lang.surroundWith.Surrounder;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.GroovySurrounderByClosure;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open.*;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.GroovyWithParenthesisExprSurrounder;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.GroovyWithTypeCastSurrounder;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.GroovyWithWithExprSurrounder;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.conditions.GroovyWithIfElseExprSurrounder;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.conditions.GroovyWithIfExprSurrounder;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.conditions.GroovyWithWhileExprSurrounder;
import java.util.ArrayList;
import java.util.List;
/**
* User: Dmitry.Krasilschikov
* Date: 22.05.2007
*/
public class GroovyStmtsSurroundDescriptor extends GroovySurroundDescriptor {
private static final Surrounder[] stmtsSurrounders = new Surrounder[]{
new GroovyWithWithStatementsSurrounder(),
new GroovyWithIfSurrounder(),
new GroovyWithIfElseSurrounder(),
new GroovyWithTryCatchSurrounder(),
new GroovyWithTryFinallySurrounder(),
new GroovyWithTryCatchFinallySurrounder(),
new GroovyWithWhileSurrounder(),
new GroovySurrounderByClosure(),
new GroovyWithShouldFailWithTypeStatementsSurrounder(),
};
/********** ***********/
private static final Surrounder[] exprSurrounders = new Surrounder[]{
new GroovyWithParenthesisExprSurrounder(),
new GroovyWithTypeCastSurrounder(),
new GroovyWithWithExprSurrounder(),
new GroovyWithIfExprSurrounder(),
new GroovyWithIfElseExprSurrounder(),
new GroovyWithWhileExprSurrounder()
};
public static Surrounder[] getStmtsSurrounders() {
return stmtsSurrounders;
}
public static Surrounder[] getExprSurrounders() {
return exprSurrounders;
}
@NotNull
public Surrounder[] getSurrounders() {
List<Surrounder> surroundersList = new ArrayList<Surrounder>();
ContainerUtil.addAll(surroundersList, exprSurrounders);
ContainerUtil.addAll(surroundersList, stmtsSurrounders);
return surroundersList.toArray(new Surrounder[0]);
}
}
@@ -0,0 +1,46 @@
/*
* Copyright 2000-2011 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.plugins.groovy.completion
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.xml.XmlText
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import org.intellij.plugins.intelliLang.inject.TemporaryPlacesRegistry
import org.jetbrains.plugins.groovy.GroovyFileType
/**
* @author peter
*/
class InjectedGroovyTest extends LightCodeInsightFixtureTestCase {
public void testTabMethodParentheses() {
myFixture.configureByText("a.xml", """<groovy>
String s = "foo"
s.codePo<caret>charAt(0)
</groovy>""")
def host = PsiTreeUtil.findElementOfClassAtOffset(myFixture.file, myFixture.editor.caretModel.offset, XmlText, false)
TemporaryPlacesRegistry.getInstance(project).getLanguageInjectionSupport().addInjectionInPlace(GroovyFileType.GROOVY_LANGUAGE, host);
myFixture.completeBasic()
myFixture.type('\t')
myFixture.checkResult("""<groovy>
String s = "foo"
s.codePointAt(<caret>0)
</groovy>""")
}
}
@@ -334,6 +334,10 @@ public class GroovyHighlightingTest extends LightCodeInsightFixtureTestCase {
doTest(new UnassignedVariableAccessInspection());
}
public void testMultipleVarNotAssigned() {
doTest(new UnassignedVariableAccessInspection());
}
public void testTestMarkupStubs() {
doTest();
}
@@ -1,11 +1,5 @@
package org.jetbrains.plugins.groovy.lang.surroundWith;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.GroovyWithParenthesisExprSurrounder;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.GroovyWithTypeCastSurrounder;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.GroovyWithWithExprSurrounder;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.conditions.GroovyWithIfElseExprSurrounder;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.conditions.GroovyWithIfExprSurrounder;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.expressions.conditions.GroovyWithWhileExprSurrounder;
import org.jetbrains.plugins.groovy.util.TestUtils;
/**
@@ -14,12 +8,13 @@ import org.jetbrains.plugins.groovy.util.TestUtils;
*/
public class SurroundExpressionTest extends SurroundTestCase {
public void testBrackets1() throws Exception { doTest(new GroovyWithParenthesisExprSurrounder()); }
public void testIf1() throws Exception { doTest(new GroovyWithIfExprSurrounder()); }
public void testIf_else1() throws Exception { doTest(new GroovyWithIfElseExprSurrounder()); }
public void testType_cast1() throws Exception { doTest(new GroovyWithTypeCastSurrounder()); }
public void testWhile1() throws Exception { doTest(new GroovyWithWhileExprSurrounder()); }
public void testWith2() throws Exception { doTest(new GroovyWithWithExprSurrounder()); }
public void testBrackets1() throws Exception { doTest(new ParenthesisExprSurrounder()); }
public void testIf1() throws Exception { doTest(new IfExprSurrounder()); }
public void testIf_else1() throws Exception { doTest(new IfElseExprSurrounder()); }
public void testType_cast1() throws Exception { doTest(new TypeCastSurrounder()); }
public void testType_cast2() throws Exception { doTest(new TypeCastSurrounder()); }
public void testWhile1() throws Exception { doTest(new WhileExprSurrounder()); }
public void testWith2() throws Exception { doTest(new WithExprSurrounder()); }
@Override
protected String getBasePath() {
@@ -1,7 +1,5 @@
package org.jetbrains.plugins.groovy.lang.surroundWith;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.GroovySurrounderByClosure;
import org.jetbrains.plugins.groovy.lang.surroundWith.surrounders.surroundersImpl.blocks.open.*;
import org.jetbrains.plugins.groovy.util.TestUtils;
/**
@@ -17,16 +15,18 @@ public class SurroundStatementsTest extends SurroundTestCase {
return TestUtils.getTestDataPath() + "groovy/surround/statements/";
}
public void testClosure1() throws Exception { doTest(new GroovySurrounderByClosure()); }
public void testClosure2() throws Exception { doTest(new GroovySurrounderByClosure()); }
public void testClosure3() throws Exception { doTest(new GroovySurrounderByClosure()); }
public void testIf1() throws Exception { doTest(new GroovyWithIfSurrounder()); }
public void testIf_else1() throws Exception { doTest(new GroovyWithIfElseSurrounder()); }
public void testShouldFailWithType() throws Exception { doTest(new GroovyWithShouldFailWithTypeStatementsSurrounder()); }
public void testTry_catch1() throws Exception { doTest(new GroovyWithTryCatchSurrounder()); }
public void testTry_catch_finally() throws Exception { doTest(new GroovyWithTryCatchFinallySurrounder()); }
public void testTry_finally1() throws Exception { doTest(new GroovyWithTryFinallySurrounder()); }
public void testWhile1() throws Exception { doTest(new GroovyWithWhileSurrounder()); }
public void testWith2() throws Exception { doTest(new GroovyWithWithStatementsSurrounder()); }
public void testClosure1() throws Exception { doTest(new SurrounderByClosure()); }
public void testClosure2() throws Exception { doTest(new SurrounderByClosure()); }
public void testClosure3() throws Exception { doTest(new SurrounderByClosure()); }
public void testIf1() throws Exception { doTest(new IfSurrounder()); }
public void testIf_else1() throws Exception { doTest(new IfElseSurrounder()); }
public void testShouldFailWithType() throws Exception { doTest(new ShouldFailWithTypeStatementsSurrounder()); }
public void testTry_catch1() throws Exception { doTest(new TryCatchSurrounder()); }
public void testTry_catch_finally() throws Exception { doTest(new TryCatchFinallySurrounder()); }
public void testTry_finally1() throws Exception { doTest(new TryFinallySurrounder()); }
public void testTry_finallyFormatting() throws Exception { doTest(new TryFinallySurrounder()); }
public void testWhile1() throws Exception { doTest(new WhileSurrounder()); }
public void testWith2() throws Exception { doTest(new WithStatementsSurrounder()); }
public void testFor1() throws Exception { doTest(new ForSurrounder()); }
}
@@ -25,6 +25,6 @@ public abstract class SurroundTestCase extends LightGroovyTestCase {
}
});
assertEquals(data.get(1), myFixture.getFile().getText().trim());
myFixture.checkResult(data.get(1));
}
}
@@ -0,0 +1,70 @@
/*
* Copyright 2000-2011 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.plugins.groovy.lang.surroundWith
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import com.intellij.codeInsight.generation.surroundWith.SurroundWithHandler
import com.intellij.openapi.actionSystem.Separator
/**
* @author peter
*/
class SurrounderOrderTest extends LightCodeInsightFixtureTestCase {
public void testStatementSurrounders() {
def names = getSurrounders("<selection>println a</selection>")
assertOrderedEquals names,
"if", "if / else", "while",
"{ -> ... }.call()",
"for", "try / catch", "try / finally", "try / catch / finally",
"shouldFail () {...}",
"(expr)", "((Type) expr)",
"with () {...}"
}
public void testInnerExpressionSurrounders() {
def names = getSurrounders("boolean a; println <selection>a</selection>")
assertOrderedEquals names, "(expr)", "((Type) expr)"
}
public void testOuterExpressionSurrounders() {
def names = getSurrounders("boolean a; <selection>a</selection>")
assertOrderedEquals names,
"if", "if / else", "while",
"{ -> ... }.call()",
"for", "try / catch", "try / finally", "try / catch / finally",
"shouldFail () {...}",
"(expr)", "((Type) expr)",
"with () {...}",
"if (expr)", "if (expr) / else", "while (expr)", "with (expr)"
}
private List<String> getSurrounders(final String fileText) {
myFixture.configureByText("a.groovy", fileText)
def actions = SurroundWithHandler.buildSurroundActions(project, myFixture.editor, myFixture.file, null)
def names = []
for (action in actions) {
if (action instanceof Separator) {
break
}
def text = action.templatePresentation.text
names << text.substring(text.indexOf('. ') + 2)
}
return names
}
}
@@ -0,0 +1,7 @@
println foo
<selection>expr</selection>
-----
println foo
((<caret>) expr)
@@ -0,0 +1,5 @@
<selection>println "foo"</selection>
-----
for (<caret>) {
println "foo"
}
@@ -1,7 +1,9 @@
<selection>a - b
a - b</selection>
println foo
-----
shouldFail() {
a - b
a - b
}
}
println foo
@@ -0,0 +1,12 @@
def foo() {
<selection>println hello
println hello</selection>
}
-----
def foo() {
try {
<caret>println hello
println hello
} finally {
}
}
@@ -1,7 +1,9 @@
<selection>a - b
a - b</selection>
println foo
-----
with() {
a - b
a - b
}
}
println foo
@@ -0,0 +1,9 @@
def args = ["one", "two", "three"]
def (one, two, three) = args
one.toString()
def foo
<warning descr="Variable 'foo' might not be assigned">foo</warning>.toString()
(args, foo) = [2, 3]
args.toString()
foo.toString()
@@ -18,15 +18,14 @@ package com.intellij.uiDesigner.actions;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.ui.ListCellRendererWrapper;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.*;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.uiDesigner.GuiDesignerConfiguration;
import com.intellij.uiDesigner.UIDesignerBundle;
import com.intellij.uiDesigner.radComponents.LayoutManagerRegistry;
@@ -176,9 +175,10 @@ public class CreateFormAction extends AbstractCreateFormAction {
});
myBaseLayoutManagerCombo.setModel(new DefaultComboBoxModel(LayoutManagerRegistry.getNonDeprecatedLayoutManagerNames()));
myBaseLayoutManagerCombo.setRenderer(new ColoredListCellRenderer() {
protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
append(LayoutManagerRegistry.getLayoutManagerDisplayName((String) value), SimpleTextAttributes.REGULAR_ATTRIBUTES);
myBaseLayoutManagerCombo.setRenderer(new ListCellRendererWrapper<String>(myBaseLayoutManagerCombo.getRenderer()) {
@Override
public void customize(JList list, String value, int index, boolean selected, boolean hasFocus) {
setText(LayoutManagerRegistry.getLayoutManagerDisplayName(value));
}
});
myBaseLayoutManagerCombo.setSelectedItem(GuiDesignerConfiguration.getInstance(project).DEFAULT_LAYOUT_MANAGER);
@@ -41,7 +41,7 @@ public class FormRelatedFilesProvider extends GotoRelatedProvider {
@NotNull
@Override
public List<GotoRelatedItem> getItems(PsiElement context) {
public List<? extends GotoRelatedItem> getItems(@NotNull PsiElement context) {
PsiClass psiClass = PsiTreeUtil.getParentOfType(context, PsiClass.class, false);
if (psiClass != null) {
List<PsiFile> forms = FormClassIndex.findFormsBoundToClass(psiClass);
+7 -7
View File
@@ -992,9 +992,11 @@
<refactoring.moveHandler implementation="com.intellij.refactoring.move.moveInner.MoveInnerToUpperOrMembersHandler"/>
<refactoring.moveHandler implementation="com.intellij.refactoring.anonymousToInner.MoveAnonymousToInnerHandler"/>
<refactoring.moveClassHandler implementation="com.intellij.refactoring.move.moveClassesOrPackages.MoveJavaClassHandler"/>
<moveFileHandler implementation="com.intellij.refactoring.move.moveClassesOrPackages.MoveJavaFileHandler"/>
<refactoring.moveMemberHandler language="JAVA" implementationClass="com.intellij.refactoring.move.moveMembers.MoveJavaMemberHandler"/>
<moveFileHandler implementation="com.intellij.refactoring.move.moveClassesOrPackages.MoveJavaFileHandler" id="java"/>
<refactoring.moveClassHandler implementation="com.intellij.refactoring.move.moveClassesOrPackages.MoveJavaClassHandler" id="java"/>
<refactoring.moveMemberHandler language="JAVA" implementationClass="com.intellij.refactoring.move.moveMembers.MoveJavaMemberHandler" id="java"/>
<refactoring.moveInnerHandler language="JAVA" implementationClass="com.intellij.refactoring.move.moveInner.MoveJavaInnerHandler" id="java"/>
<refactoring.safeDeleteProcessor implementation="com.intellij.refactoring.safeDelete.JavaSafeDeleteProcessor" id="javaProcessor"/>
@@ -1041,10 +1043,8 @@
<gotoTargetRendererProvider implementation="com.intellij.codeInsight.navigation.JavaGotoTargetRendererProvider"/>
<renameHandler implementation="com.intellij.refactoring.rename.DirectoryAsPackageRenameHandler"/>
<rename.inplace.resolveSnapshotProvider
language="JAVA"
implementationClass="com.intellij.refactoring.rename.inplace.JavaResolveSnapshotProvider"
/>
<rename.inplace.resolveSnapshotProvider language="JAVA"
implementationClass="com.intellij.refactoring.rename.inplace.JavaResolveSnapshotProvider"/>
<updateAddedFileProcessor implementation="com.intellij.psi.impl.file.JavaUpdateAddedFileProcessor"/>
<findUsagesHandlerFactory implementation="com.intellij.find.findUsages.JavaFindUsagesHandlerFactory" id="java"
@@ -41,14 +41,10 @@ public class HtmlWebBrowserUrlProvider extends WebBrowserUrlProvider {
@Override
public boolean canHandleElement(@NotNull final PsiElement element) {
final PsiFile file = element instanceof PsiFile ? (PsiFile) element : element.getContainingFile();
if (file == null){
return false;
}
final Language language = file.getViewProvider().getBaseLanguage();
return HTMLLanguage.INSTANCE == language || XHTMLLanguage.INSTANCE == language;
return file != null && isHtmlFile(file);
}
public static boolean isAvailableFor(@NotNull final PsiFile file) {
protected static boolean isHtmlFile(@NotNull final PsiFile file) {
final Language language = file.getLanguage();
return language instanceof HTMLLanguage || language instanceof XHTMLLanguage;
}
@@ -39,11 +39,7 @@ import java.util.Set;
public class HtmlGotoRelatedProvider extends GotoRelatedProvider {
@NotNull
@Override
public List<GotoRelatedItem> getItems(PsiElement context) {
if (context == null) {
return Collections.emptyList();
}
public List<? extends GotoRelatedItem> getItems(@NotNull PsiElement context) {
final PsiFile file = context.getContainingFile();
if (file == null || !isAvailable(file)) {
return Collections.emptyList();